【问题标题】:Vue binding overrides element attributeVue 绑定覆盖元素属性
【发布时间】:2017-11-09 22:25:53
【问题描述】:

我有一个渲染 HTML 输入的组件:

<input
    :placeholder="placeholder"
    v-model="value"
    type="text"
    :disabled="disabled"
    :readOnly="readOnly"
    @focus="onFocus"
/>

请注意,type 未绑定/反应。

当我将此组件放入另一个组件中并将一个对象绑定到它时,type 会被覆盖。

 <my-input v-bind="{type: 'foobar'}"></my-input>

这是by design 还是bug


示例(检查 HTML 中的input[type]):

const Input = {
    template: '<input type="text"/>'
    //                      ^^^^ "text" gets overriden to "foobar"
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});
<script src="http://vuejs.org/js/vue.min.js"></script>
<div id="demo">
    <my-input v-bind="{type: 'foobar'}"></my-input>
</div>

【问题讨论】:

  • 看起来像一个错误。

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

我在一个问题中回答了这个问题,这是预期的

https://github.com/vuejs/vue/issues/5846#issuecomment-307098682

但是,您可以通过将 attrs 添加为 props 来忽略它们并忽略它们

const Input = {
    props: ['type'],
    template: '<input type="text"/>'
    //                      ^^^^ "text" won't get overriden
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});

class 等其他属性被合并,但 type 只能被覆盖

【讨论】:

  • 我想你是想摆脱评论? “文本”不会被覆盖
  • 是的,我忘了编辑评论。现在已修复 :) 谢谢
【解决方案2】:

VueJS 将组件属性添加到组件模板的第一个子节点。

看看这个小提琴

http://jsfiddle.net/8hzhvrng/

my-input 有一个 inputroot 孩子,然后它得到 type="password"

my-input2 有一个 div 根子节点,它获取 type="number"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 2014-02-21
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    相关资源
    最近更新 更多