如果我有一个包含如下字段属性的数据结构,那么如何在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标记中使用胡子语法,而且我不能将它绑定到data-*属性,因为属性是值的一部分,例如,data-autocomplete和data-selected?
发布于 2018-09-16 16:14:49
您不能使用普通的数据绑定语法来实现这一点。您将需要使用自定义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
钩子来删除现有的数据-*属性。
发布于 2018-09-16 16:29:16
如果将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>`
});
https://stackoverflow.com/questions/52355922
复制相似问题