Vue组件通信09-多层级组件通信(爷爷到孙子-传方法)-$listener

    科技2025-10-10  13

    components/Parent.vue

    <template> <div> 我是父组件 <br> 这里显示父级的msg:{{msg}} <Son :msg="msg" @changeMsg="changeMsg"></Son> </div> </template> <script> /* $listeners: 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。 */ import Son from '../components/Son'; export default { components: { Son, }, data() { return { msg: "我是父级的msg", title:"我是父级传递的title" }; }, methods: { changeMsg(msg) { this.msg = msg; }, }, } </script> <style scoped> </style>

    components/Son.vue

    <template> <div> <hr> 我是子组件 <br> <button @click="handleMsg">点击改变msg</button> <Grandson v-bind="$attrs" v-on="$listeners"></Grandson> </div> </template> <script> import Grandson from '../components/Grandson'; export default { components: { Grandson, }, inheritAttrs:false, created() { console.log("这里是子组件,改变之前的msg为:" + this.$attrs.msg); }, updated () { console.log("这里是子组件,改变之后的msg为:" + this.$attrs.msg); }, methods: { handleMsg() { this.$listeners.changeMsg("子组件更改的msg"); } }, } </script> <style scoped> </style>

    components/Grandson.vue

    <template> <div> <hr> 我是孙子组件 <br> <button @click="handleMsg">点击改变msg</button> {{$attrs.title}} </div> </template> <script> export default { inheritAttrs:false, beforeUpdate () { console.log("这里是孙子组件,改变之前的msg为:" + this.$attrs.msg); }, updated () { console.log("这里是孙子组件,改变之后的msg为:" + this.$attrs.msg); }, methods: { handleMsg() { this.$listeners.changeMsg("孙子组件更改的msg"); } }, } </script> <style scoped> </style>

    App.vue

    <template> <div id="app"> <Parent></Parent> </div> </template> <script> import Parent from './components/Parent' export default { name: 'App', components: { Parent, } } </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>

    效果截图:

    Processed: 0.010, SQL: 8