多层父子组件通信通信方式一(爷爷和孙子通话)
- vue.js之多层父子组件通信方式二(provide和inject)
$attrs
,包含了父组件作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外);当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过v-bind="$attrs"
传入内部组件。$listeners
,包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器,它可以通过v-on="$listeners"
传入内部组件。- 假如有组件A CompA(爷爷)、组件B CompB(爸爸)、组件C CompC(孙子),App.vue调用组件A,组件A调用组件B,组件B调用组件C,且组件A要给组件C(孙子)传数据,其中组件B(爸爸)也要收数据。
App.vue
<template>
<div id="app">
<CompA title="123"></CompA>
</div>
</template>
<script>
import CompA from "./components/CompA";
export default {
name: 'App',
components: {
CompA,
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
组件A
<template>
<div>
CompA
<!-- 通过$attrs传给CompB,CompC -->
<!-- $attrs收集属性 $listeners收集事件-->
<CompB title="my name is CompA" v-bind="$attrs" v-on="$listeners"></CompB>
</div>
</template>
<script>
import CompB from "./CompB";
export default {
// 爷爷要给孙子CompA传话
//和$attrs结合起来用
inheritAttrs: false,
components: {
CompB,
},
mounted () {
// attrs 如果没有在props里面定义的参数,都会到这里来
console.log(this.$attrs);
console.log(this);
},
};
</script>
<style scoped>
</style>
组件B
<template>
<div>
CompB
<CompC v-bind="$attrs"></CompC>
</div>
</template>
<script>
import CompC from "./CompC";
export default {
components: {
CompC,
},
mounted () {
console.log(this.$attrs);
console.log(this.$listener);
},
}
</script>
<style lang="scss" scoped>
</style>
组件C
<template>
<div>
CompC
{{$attrs.title}}
</div>
</template>
<script>
export default {
//收到了爷爷CompA说的话
mounted () {
console.log(this.$attrs);
},
}
</script>
<style lang="scss" scoped>
</style>
inheritAttrs 属性
inheritAttrs:false
是不允许组件绑定的未注册属性渲染到组件根节点上的,默认是true。
<template>
<div>
<button :disabled="$attrs.disabled">click</button>
</div>
</template>
<script>
export default {
inheritAttrs: false,
}
</script>
<style lang="sass" scoped>
</style>