如果我的数据结构包含如下字段属性,如何在html内输出dataAttributes
值?
var app3 = new Vue({
el: '#app-3',
data: {
field: {
type: 'text,
name: 'First Name',
class: 'form-control js-user-lookup',
dataAttributes: 'data-autocomplete-url=api/users data-selected=123',
}
}
})
<input :type="field.type"
:id="field.name"
:name="field.name"
:class="field.class"
{{field.dataAttributes}} />
您不能在html标记内使用mustache语法,我也无法将其绑定到data- *属性,因为该属性是值的一部分,例如data-autocomplete-url和data-selected?
答案 0 :(得分:0)
您不能使用简单的数据绑定语法来做到这一点。您将需要使用自定义directive
。看起来像这样。
<input :name="field.name" v-data-binder="field.dataAttributes" />
您的指令定义将类似于:
// 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
}
})
每当传递给指令的值发生更改时,您还需要在指令定义中使用updated
钩来删除现有的 data-* 属性。
答案 1 :(得分:0)
如果您将dataAttributes字符串作为javascript对象传递并像v-bind =“ myobject”那样绑定它,则可以更轻松地实现。如果不可能的话,您可以通过计算属性进行转换 查看下面的示例
<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>`
});