非Prop特性
一、非Prop特性
1.替换/合并已有的特性
<div id="app">
<my-cmp class="my-cmp" type='text'></my-cmp>
</div>
<script>
Vue.component('my-cmp',{
template: `
<input type='date' class='b'>
`
});
const vm = new Vue({
el: '#app'
});
</script>
在这种情况下,我们定义了两个不同的 class 的值:
- my-cmp,这是在组件的模板内设置好的
- b,这是从组件的父级传入的
对于绝大多数特性来说,从外部提供给组件的值会替换掉组件内部设置好的值。所以如果传入 type=“text” 就会替换掉 type=“date” 并把它破坏!庆幸的是,class 和 style 特性会稍微智能一些,即两边的值会被合并起来,从而得到最终的值:my-cmp b。
2.禁用特性继承
<div id="app">
<my-cmp type='radio'></my-cmp>
</div>
<script>
Vue.component('my-cmp',{
template: `
<label>
<input />
</label>
`
});
const vm = new Vue({
el: '#app'
});
</script>
如果不希望组件的根元素继承特性,那么可以在组件选项中设置 inheritAttrs: false
。如:
Vue.component('my-cmp',{
inheritAttrs: false,
template: `
<label>
<input />
</label>
`
});
在这种情况下,非常适合去配合实例的 $attrs 属性使用,这个属性是一个对象,键名为传递的特性名,键值为传递特性值。
Vue.component('my-cmp',{
inheritAttrs: false,
template: `
<label>
<input v-bind='$attrs'/>
</label>
`
});
注意:inheritAttrs: false 选项不会影响 style 和 class 的绑定。