一般,組件都會嵌套,而我們知道常用的父子組件傳參通過props,vuex,eventBus等。。。
但是,props只是適用了父子,但是 孫組件 如何到父組件呢?,有一些小項目,整個項目我就只有這么一個需求,,不可能為了這個就用了vuex吧,這樣總覺得不對,
一級一級往上傳,孫傳子,子傳父,也比較難以維護,所以我個人也不建議
在vue 2.4版本,vue 增加了$attrs $listeners ,具體怎么用呢,大家可以去官網看看,我這里只說解決我上面提出的問題、
直接上代碼:
定義a組件,b組件,c組件,a嵌套b,b嵌套c,如何將 c 組件的參數傳到a組件呢?
a組件:
<template> <div class="hello"> <bbb @refresh="refresh"></bbb> </div> </template> <script> import bbb from "./b"; export default { data() { return {}; }, components: { bbb }, methods:{ refresh(){ console.log("觸發了refresh") } } }; </script>
b組件:
<template> <div class="hello"> <ccc v-bind="$attrs" v-on="$listeners"></ccc> </div> </template> <script> import ccc from "./c"; export default { data() { return {}; }, components: { ccc } }; </script>
c組件:
<template> <div class="hello"> <button @click="clickHandle">觸發refresh</button> </div> </template> <script> export default { data() { return {}; }, methods: { clickHandle() { console.log("9"); this.$emit("refresh"); } } }; </script>
而我在HelloWorld.vue文件中引用a組件
HelloWorld.vue:
<template> <div class="hello"> <aaa @refresh="refresh"></aaa> </div> </template> <script> import aaa from './a' export default { data () { return { } }, mounted(){ console.log("sss222",this.$listeners) }, methods:{ refresh(){ console.log("觸發refresh") console.log("sss",this.$attrs) } }, components:{ aaa } } </script>
點擊,效果如同下面:
但是我開始的時候在HelloWorld 中也寫了跟 a 組件 一樣的觸發事件,但是卻沒有可以觸發,所以,我這個解決的辦法也就 三層, 到了嵌套四層的話,就不行了,,,
所以當嵌套到4層的時候,怎么解決呢?懂的話,就告訴我吧,阿里嘎多