官网的文档简短而又不清晰,实在是看不懂,只好自己找代码验证来看看是什么意思:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/3.1.5/vue.global.js"></script>
</head>
<body>
<div id="app">
<father :v1="'value1'" :v2="'value2'" :v3="'value3'"></father>
</div>
</body>
</html>
<script>
const app = Vue.createApp({
data() {
return {}
},
})
app.component('father', {
// inheritAttrs: false,
props: ['v1'],
template: ` <div><p>v1 is {{v1}}</p>
<son v-bind='$attrs' :some="1"></son>
</div>`,
created() {
console.log('father:', this.$attrs)
}
})
app.component('son', {
// inheritAttrs: false,
props: ['v2'],
template: `<div><p>v2 is {{v2}}</p>
<grandSon v-bind='$attrs'></grandSon>
</div>`,
created() {
console.log('son:', this.$attrs)
}
})
app.component('grandSon', {
props: ['v3'],
template: `<p>v3 is {{v3}}</p>`,
created() {
console.log('grandSon:', this.$attrs)
}
})
app.mount('#app')
</script>
页面显示的结果:
v1 is value1
v2 is value2
v3 is value3
页面源代码:
<div id="app" data-v-app="">
<div v2="value2" v3="value3"> <!-- 这是father -->
<p>v1 is value1</p>
<div v3="value3" some="1"> <!-- 这是 son-->
<p>v2 is value2</p>
<p some="1">v3 is value3</p> <!-- 这是 grandSon -->
</div>
</div>
</div>
控制台打印是当前组件的$attrs:
father: Proxy {v2: "value2", v3: "value3", __vInternal: 1}
son: Proxy {v3: "value3", some: 1, __vInternal: 1}
grandSon: Proxy {some: 1, __vInternal: 1}
首选,father组件被传入了3个值,但是实际使用props接收的只有v1,v2和v3作为attributes在DOM里面渲染了。
上图的devtool 也可以说明,另外就是控制台也同时证明了。
同样son组件只是接收v2作为prop:
grandSon组件只是接收v3作为prop
father prop:v1,attributes: v2,v3
son prop:v2 ,attributes:v3,some
grandSon prop:v3,,attributes: some
发现无论是father传入的3个值v1,v2,v3还是son又传入的值':some=1',
只要不被prop传入下一层组件,那么一定是在下一层组件的$attrs,也就是说不被作为prop的值会传入下一个组件作为attrs的一员。一个组件的attrs由父组件传递以及自己自带的组合而成。
上面说的是$attrs,那么inheritAttrs则说的是attrs继承,这里的继承是控制DOM渲染,不继承也就是不渲染了,但是实际还是存在这个attrs的。
`inheritAttrs`属性默认是true,所以能看到上面的结论,attrs会往下传,当设置为false的时候就不会在DOM渲染从上一层继承来的attrs。
修改一下代码:
app.component('father', {
inheritAttrs: false, // 不继承
props: ['v1'],
template: ` <div><p>v1 is {{v1}}</p>
<son v-bind='$attrs' :some="1"></son>
</div>`,
created() {
console.log('father:', this.$attrs)
}
})
father组件这不继承attrs,控制台的打印没变:
father: Proxy {v2: "value2", v3: "value3", __vInternal: 1}
son: Proxy {v3: "value3", some: 1, __vInternal: 1}
grandSon: Proxy {some: 1, __vInternal: 1}
devtool这里依然可以看到attrs
但是看源代码:
<div id="app" data-v-app="">
<div> <!-- 这里是 father --> <!-- 看这行 -->
<p>v1 is value1</p>
<div v3="value3" some="1"> <!-- 这里是 son-->
<p>v2 is value2</p>
<p some="1">v3 is value3</p> <!-- 这里是 grandSon-->
</div>
</div>
</div>
DOM渲染里面的v2,v3 attrs都不存在了。
所以综合总结一下:
- $attrs就是给组件传值排除了作为prop的那部分(比如father的v2,v3),包括了(class,id)
- inheritAttrs只是用来控制attrs是否在DOM中渲染。