- 定义:non-props属性是指父组件传给子组件值,但是子组件并没有去接收,此时值会加到子组件的标签属性中。若想去掉该属性,可在子组件创建的时候加‘inheritAttrs: false’
- 如果子组件有多个根节点,只有其中一个想接收传过来的non-props属性,则可以在接收的那个加’v-bind’属性接收
如:
<!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>17</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
const app = Vue.createApp({
template: `<div><counter msg="hello"/></div>`
});
app.component('counter', {
// props: ['msg'],
template: `<div>Counter</div>
<div v-bind="$attrs">Counter</div>
<div>Counter</div>
`
})
const vm = app.mount('#root')
</script>
</body>
</html>
如果想拿到其中的一个non-props属性,则可以如下:
<script>
const app = Vue.createApp({
template: `<div><counter msg="hello" msg1="hello1"/></div>`
});
app.component('counter', {
// props: ['msg'],
template: `<div v-bind:msg="$attrs.msg">Counter</div>
<div>Counter</div>
<div>Counter</div>
`
})
const vm = app.mount('#root')
</script>
还可以在生命周期函数mounted()中获取属性
<script>
const app = Vue.createApp({
template: `<div><counter msg="hello" msg1="hello1"/></div>`
});
app.component('counter', {
// props: ['msg'],
// 组件渲染完之后会自动执行
mounted() {
console.log(this.$attrs);
},
template: `<div v-bind:msg="$attrs.msg">Counter</div>
<div>Counter</div>
<div>Counter</div>
`
})
const vm = app.mount('#root')
</script>