[Vuejs]-VueJS binding custom directives to looped components based on condition

0👍

You can do that, but need to use a different v-bind syntax.

You pass an object with keys being the HTML attribute name.

You can generate an object at runtime using Computed property names for object initialization

Try this

<ul>
 <li v-for="item in list" v-bind="{[`${item.directive}`]: ''}">{{item.name}}</li>
</ul>

0👍

I think the preferred way to achieve something like this is the following:

new Vue({
  el: '#app',
  data: {
    list: [
      { name: "test-a", directive: "v-testa" },
      { name: "test-b", directive: "v-testb" },
      { name: "test-c", directive: "v-testc" }
    ]
  },
  methods: {
  	
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>List:</h2>
  <ol>
    <li v-for="item in list" :data-directive="item.directive">
       {{ item.name }}
    </li>
  </ol>
</div>

Because if you start making up your own attributes, you run into two problems:

  1. An HTML validator will assume that your attribute is incorrect
  2. You are competing with other code which is also making up its own attributes

The data- attribute prefix has two benefits:

  1. HTML validators will ignore the attribute when doing validation
  2. JavaScript will gather these attributes into the special data object to provide easy access

So using the data- prefix allows you to work with an otherwise invalid attribute by telling the validator to ignore it.

Leave a comment