【问题标题】:Dynamically add arbitrary attributes to a Vue component element?为 Vue 组件元素动态添加任意属性?
【发布时间】:2018-06-12 10:25:12
【问题描述】:

我想创建一个组件,它可以在运行时从 Vue.data 中具有任意属性(例如 data-xxx),该组件不期望/不知道。例如,这不起作用,但在概念上:

Vue.component('text-input',{
  template: `<input type="text" v-model="value" :name="name" {{extra_atts}}>`,
  props:['value','name','extra_atts']
});

.....
//Used elsewhere in Vue app:

<text-input :value="avalue" :name="aname" :extra_atts="dynamic_atts"> </text-input>

const vm = new Vue({
  data: {
    aname: "username",
    avalue: "johnny",
    dynamic_atts: "placeholder='Your name' title='Required' data-extrainfo='arbitrary data'",
  }...

所以它会呈现为:

<input type='text' value='johnny' name='username' placeholder='Your name' title='Required' data-extrainfo='arbitrary data' />

有没有办法在 Vue 中做到这一点?

谢谢,

克里斯

【问题讨论】:

    标签: vue.js attributes vuejs2 components


    【解决方案1】:

    只需将inheritAttrs 设置为false。然后利用$attrs绑定输入元素的属性

    Vue.component('text-input',{
      inheritAttrs: false,
      template: `<input type="text" v-model="value" :name="name" v-bind="$attrs">`,
      props:['value','name']
    });
    

    现在只需像添加常规输入一样在组件上添加属性

    <text-input :value="avalue" :name="aname" placeholder='Your name' title='Required' data-extrainfo='arbitrary data'> </text-input>
    

    【讨论】:

      猜你喜欢
      • 2014-02-17
      • 2019-06-24
      • 2021-08-20
      • 2018-10-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      相关资源
      最近更新 更多