vue中组件通信父➡️子通过props
,子➡️父通过$emit
,那么父➡️孙,孙➡️父呢?
通常使用的方法是通过vuex
。如果仅仅是传递数据,而不做其他处理,使用 vuex
处理有点大材小用。
所以就有了 $attrs / $listeners
,通常配合inheritAttrs
一起使用。(注意:是2.4新增的)
📙inheritAttrs
inheritAttrs的讲解参考官网,如下图所示:
📙$attrs / $listeners
📒$attrs
-
官网讲解
-
🌰例子
- 父组件(component_parent.vue)
<template> <div> <child :parent="parentString" :info="info"></child> </div> </template>
<script> import child from "./component_child" export default { name: '', components: { child }, data() { return { parentString: "这是父组件", info: { name: "张三", address: "陕西省" } } } }; </script>
- 子组件(component_child.vue)
<template> <div> <div>{{parent}}</div> <div>子组件:{{$attrs}}</div> <grandson v-bind="$attrs" :message="message"></grandson> </div> </template>
<script> import grandson from './component_grandson.vue' export default { name: '', components: { grandson }, props: [parent], data() { return { message: "这是子组件的传值" }; }, mounted() { console.log('child', this.$attrs); //打印出Info的值,(因为parent的值已经被props接收,所以只打印出info) }, }; </script>
- component_grandson.vue
<template> <div>孙子组件:{{$attrs}}</div> </template>
<script> export default { name: '', data() { return { }; }, mounted() { console.log('grandson', this.$attrs); }, </script>
父组件的值传给了子孙组件,那子孙组件的值如何同步给父组件呢? - 父组件(component_parent.vue)
📒$listeners
- 官网讲解
- 🌰例子
- 父组件(component_parent.vue)
<template> <div> <child :parent="parentString" :info="info" @updateInfo="updateInfo"></child> </div> </template>
<script> import child from "./component_child" export default { name: '', components: { child }, data() { return { parentString: "这是父组件", info: { name: "张三", address: "陕西省" } } }, methods: { updateInfo() { console.log('更新父组件'); } }, }; </script>
- 子组件(component_child.vue)
<template> <div> <div>{{parent}}</div> <div>子组件:{{$attrs}}</div> <grandson v-bind="$attrs" :message="message" @childInfo="childInfo"></grandson> </div> </template>
<script> import grandson from './component_grandson.vue' export default { name: '', components: { grandson }, props: [parent], data() { return { message: "这是子组件的传值" }; }, mounted() { // console.log('child', this.$attrs); //打印出Info的值,(因为parent的值已经被props接收,所以只打印出info) console.log('child-listeners', this.$listeners); //updateInfo:f }, methods: { childInfo() { console.log('更新子组件'); } }, }; </script>
- component_grandson.vue
<template> <div>孙子组件:{{$attrs}}</div> </template>
<script> export default { name: '', data() { return { }; }, mounted() { //console.log('grandson', this.$attrs); console.log('grandson-listeners', this.$listeners); //updateInfo:f childInfo:f this.$emit('updateInfo') //触发父组件中的updateInfo函数(会打印出父组件打印的值) }, </script>
- 父组件(component_parent.vue)
以上就是$attrs
和$listeners
的使用,有问题欢迎随时指出!🏄🏄🏄