Non-porps属性
父组件向子组件传递参数的时候,子组件不写任何的接受方法,这个时候父组件就会直接把属性完全复制给子组件,子组件也是可以得到属性值的。
注意:Non-porps属性会复制,props属性不会复制
如果组件不是一个根节点,复制就会失效。
在标签中使用父组件传入的属性
通过$attrs可以在组件使用父组件传入的所有属性
通过$attrs.style的形式(style是其中一个属性值名)可以使用其中一个属性
注意:使用$attrs.style形式调用props属性,无法复制使用
<h3 v-bind="$attrs">使用$attrs</h3>
<h3 v-bind:msg="$attrs.msg">使用$attrs.style</h3>
在业务逻辑中使用父组件传入的属性
和标签中使用的方式一样
methods: {
btnClick() {
alert(this.$attrs.msg);
alert(this.$attrs);
}
}
不接受传入参数
inheritAttrs:false
app.component('GlobalInheritAttrs', {
inheritAttrs: false,
template: `
<h3>不接受传入参数</h3>
`
});
Demo22.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div>
<h4>Non-porps属性</h4>
<p>父组件向子组件传递参数的时候,子组件不写任何的接受方法,这个时候父组件就会直接把属性完全复制给子组件,子组件也是可以得到属性值的。</p>
<p>注意:Non-porps属性会复制,props属性不会复制</p>
<p>如果组件不是一个根节点,复制就会失效。</p>
<h4>在标签中使用父组件传入的属性</h4>
<p>通过$attrs可以在组件使用父组件传入的所有属性</p>
<p>通过$attrs.style的形式(style是其中一个属性值名)可以使用其中一个属性。</p>
<p>注意:使用$attrs.style形式调用props属性,无法复制使用</p>
<h4>在业务逻辑中使用父组件传入的属性</h4>
<p>和标签中使用的方式一样</p>
<h4>不接受传入参数</h4>
<p>inheritAttrs:false</p>
<br>
</div>
<div id="app"></div>
</body>
<script>
const app = Vue.createApp({
template: `
<div>Non-porps属性</div>
<global msg="Msg属性" name="Name属性" propMsg="PropMsg属性"/>
<br>
<div>在标签中使用父组件传入的属性</div>
<global-attrs msg="Msg属性" name="Name属性" propMsg="PropMsg属性"/>
<br>
<br>
<div>不接受传入参数</div>
<global-inherit-attrs msg="Msg属性" name="Name属性" propMsg="PropMsg属性"/>
<br>
`
});
app.component('global', {
props: ['propMsg'],
template: `
<h3>Non-porps属性会复制,props属性不会复制</h3>
`
});
app.component('GlobalAttrs', {
props: ['propMsg'],
methods: {
btnClick() {
alert(this.$attrs.msg);
alert(this.$attrs);
}
},
template: `
<h3>组件不是一个根节点,复制就会失效</h3>
<h3 v-bind="$attrs">使用$attrs</h3>
<h3 v-bind:msg="$attrs.msg">使用$attrs.style</h3>
<h3 v-bind:propMsg="$attrs.propMsg">使用$attrs.style调用props属性,无法复制使用</h3>
<button @click="this.btnClick">在业务逻辑中使用父组件传入的属性</button>
`
});
app.component('GlobalInheritAttrs', {
inheritAttrs: false,
template: `
<h3>不接受传入参数</h3>
`
});
const vm = app.mount("#app");
</script>
</html>