[Vuejs]-Vue.js How to output attribute inside html tag when attribute name is included in value?

0👍

You cannot do that with plain data-binding syntax. You will need to use the custom directive. It will look like this.

<input :name="field.name" v-data-binder="field.dataAttributes" />

Your directive definition will be something like:

// Register a global custom directive called `v-focus`
Vue.directive('data-binder', {
    // When the bound element is inserted into the DOM...
    inserted: function (el, binding) {
        // Perform data attribute manipulations here.

        // 1. Parse the string into proper key-value object
        // binding.value

        // 2. Iterate over the keys of parsed object

        // 3. Use JavaScript *dataset* property to set values
    }
})

You will also need updated hook in your directive definition to remove existing data-* attributes whenever the value passed to the directive changes.

0👍

You can more easily do it if you have the dataAttributes string passed as a javascript object and just bind it like that v-bind=”myobject”. If not possible you can transform it via a computed property
Check below example

<div id="app">
</div>



 var instance = new Vue({
  el:'#app',
  data:function(){
    return {
      inputType:'password',
      fieldAttributes:"data-autocomplete-url=api/users data-selected=123"
   };
 },
  computed:{
    getDataAttributes:function(){
     var attributes = this.fieldAttributes.split(' ');

    var attributesO = {};
    for(var a=0;a<attributes.length;a++){
      var attribute = attributes[a];
      var attribute_ar = attribute.split('=');
      attributesO[attribute_ar[0]] = attribute_ar[1];
    }

     return attributesO;
    }
 },
 methods:{
   getAttribute:function(){
     alert(this.$refs.myinput.dataset.selected)
   }
  },
   template:`<div>
    <input ref="myinput" v-on:click="getAttribute" :type="inputType"  v-bind="getDataAttributes" />
    </div>`
   });

Leave a comment