首先看一下vue的官网介绍
透传 Attributes 是指由父组件传入,且没有被子组件声明为 props 或是组件自定义事件的 attributes 和事件处理函数。
当我们需要跨多层页面,父向子代传值的话 ,这时候用就可以用$attrs 来传值就非常的方便,顾名思义,它是利用自定义属性来传值的例如:
<template>
<div>
<!-- 父组件 -->
我是父组件
<Son
title="我是父组件传来的"
></Son>
</div>
</template>
<script>
import Son from './components/son.vue';
export default {
components: { Son }
}
</script>
<style>
</style>
<template>
<div>
我是儿子组件
<Sun></Sun>
</div>
</template>
<script>
import Sun from './sun.vue';
export default {
components: { Sun, }
,
created() {
console.log(this.$attrs);
}
}
</script>
<style>
</style>
此时页面打印
直接在子组件打印的话会直接打印出父组件的自定义属性的值,但是如果直接在孙子组件以及更深层组件打印的话会是以一个空对象
此时如果要想要父组件的值的话,就要开启深度监听,在父组件的子组件加上 v-bind="$attrs"
如果要下一层继续获取上一层的值得话,就需要继续在下一层组件里加上v-bind="$attrs"
<template>
<div>
我是儿子组件
<Sun
v-bind="$attrs"
></Sun>
</div>
</template>
<script>
import Sun from './sun.vue';
export default {
components: { Sun, }
,
created() {
console.log(this.$attrs);
}
}
</script>
<style>
</style>
但是此时我们观察到dom节点
你传入的值在节点中显示了这就是透传 “attribute”
“透传 attribute”指的是传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者
v-on
事件监听器。当一个组件以单个元素为根作渲染时,透传的 attribute 会自动被添加到根元素上。
如果我们不想要把传入的值显示在dom节点中,且想要用$attrs传值的话就需要 禁用 Attributes 继承
inheritAttrs:false
此时就没有在dom节点中显示了