VueJS Use prop as data-attribute value

2019-03-30 06:45发布

I am really struggling with the following scenario:

Some index page:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8"/>
  </head>
  <body>
    <div id="app">

      <ul>
        <li>some existing option</li>
        <example-component :foo="foo" :bar="bar"/>
      </ul>

      <a @click.prevent="showDetail(1, 'abc')" href="#" >Click ME!</a>

    </div>


    <script src="app.js"></script>


  </body>
</html>

Some single file component:

<template>
    <li><a v-show="checkBool" data-toggle="tab" class="some-class" href="#container-div" data-tab-url="{{ this.foo }}">{{ this.bar }}</a></li>
</template>



<script>
export default {

  props: ['foo', 'bar'],


  computed: {
    checkBool: function() {
      return (this.foo != undefined && this.bar != undefined )
    }

  }

}
</script>

And the app.js looks something like this:

import Vue from 'vue'

Vue.component('example-component', require('ExampleComponent.vue'));

const app = new Vue({
    el: '#app',

    props: [
      'foo',
      'bar'
    ],

    data: {
      foo: '',
      bar: ''
    },

     methods: {
      showDetail: function (foo, bar) {
        this.foo = foo,
        this.bar = bar
      }
  }
});

I am using babel with webpack under a laravel instalation.

The scenario is like this:

  • When I click the Click ME! link, foo and bar are updated and passed to the component (This part is working)
  • The computed property, named checkBool for this example becomes true, so I will then see the new list item (This part is working)
  • New list item, has a link, with the text correctly set to bar (This part is also working)

At this point I know that the values setting and communication between component and parent is working properly, however data-tab-url="{{ this.foo }}" part is driving me crazy.

Instead of parsing the moustache syntax as expected and return data-tab-url="1", I get a parsed/escaped value of everything between quotes.

Something like data-tab-url="%7B%7B+this.foo+%7D%7D".

Now, how do I prevent the encode from happening? From what I've read, there used to be a way in vuejs 1.*. Using three brackets: {{{ this.foo }}} but it's now deprecated in favor of v-html which I cannot use for my example.

1条回答
仙女界的扛把子
2楼-- · 2019-03-30 07:16

Bind the attribute like this :data-tab-url="foo".

This will give the affected element a data-tab-url attribute with a value equal to the foo property of your component.

查看更多
登录 后发表回答