1.Non-props
概念:如果我们不用props属性但是也想使用传过来的值,这就是Non-props的含义。
const app = Vue.createApp({
data() {
return {
num: 1,
};
},
template: `
<div>
<counter msg="hello" />
</div>`,
});
app.component("counter", {
mounted() {
//在attrs属性中会有传过来的值
console.log(this.$attrs.msg);
},
template: `
<div :msg="$attrs.msg">Counter</div>
`,
});
未加inheritAttrs:false
加了之后
2.禁止Non-props
在组件中加入inherit:false可以阻止Vue自动往最外层的组件添加传过来的值
app.component("counter", {
inheritAttrs: false,
mounted() {
console.log(this.$attrs.msg);
},
template: `
<div>Counter</div>
`,
});
3.将传过来的值绑定在标签上
app.component("counter", {
mounted() {
console.log(this.$attrs.msg);
},
template: `
// 绑定在标签上,这里可以传一些样式进来
<div :="$attrs">Counter</div>
`,
});