$attr属性介绍
包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class
和 style
除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class
和 style
除外),并且可以通过 v-bind="$attrs"
传入内部组件——在创建高级别的组件时非常有用。 ---来自vue官网
使用中的问题
template中
<div id="app">
A{{msg}}
<my-button :msg="msg" :testa="testA" :testb="testB"></my-button>
</div>
js中
let vm = new Vue({
el: "#app",
data: {
msg: "(A)",
testA: {
label: "aaa",
value: 111,
},
testB: {
label: "bbb",
value: 222,
},
},
components: {
MyButton: {
// props: ['msg'],
template: `<div>B<my-input v-bind="$attrs"></my-input></div>`,
components: {
MyInput: {
// props: ["msg"],
template:
"<div>
<span>C{{$attrs.msg}}</span>
<span>{{$attrs.testa.label}}</span>
<span>{{$attrs.testb.label}}</span></div>",
},
},
},
},
});
在使用中,发现对属性的绑定上,:testa="testA"
不支持驼峰的写法,比如这样:testA:"testA"
这种写法。经过测试发现只能全部小写或者-
隔开的写法,才能在子组件被$attrs取到。