Vue绑定覆盖元素属性

时间:2017-06-08 09:27:19

标签: javascript vue.js vuejs2 vue-component

我有一个呈现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]):

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

2 个答案:

答案 0 :(得分:1)

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

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

然而,您可以通过将它们添加为道具而忽略它们来忽略它们

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

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

答案 1 :(得分:0)

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

看这个小提琴

http://jsfiddle.net/8hzhvrng/

my-input有一个input root子项,然后它获得type="password"

my-input2有一个div root子项,它获取type="number"