小計: 開發中遇到子組件需要調用兄弟組件中的方法,如下寫個小demo記錄下心得,如果你有好的方法,請到評論區域指教
父組件示例代碼:
組件功能解析: 通過$emit獲取子組件事件,通過$ref調用子組件中事件,實現子組件二的click事件調用兄弟組件一中的事件
<template><div><!-- 子組件1 --><son1 ref="borther" :dataFromFather="dataFromFather"></son1><!-- 子組件2 --><son2 @triggerBrotherMethods="triggerBrotherMethods" :dataFromFather="dataFromFather"></son2></div>
</template><script>
// 引入子組件一
import son1 from './son1'
// 引入子組件二
import son2 from './son2'export default {data() {return {dataFromFather: []}},// 注冊子組件components: {son1,son2},methods: {// 子組件2中click事件triggerBrotherMethods() {// 父組件通過$ref調用子組件1中的事件方法this.$refs.borther[0].bortherMethods()},}
}
</script><style lang="less" scoped>
/* .... */
</style>
子組件一
組件功能解析: 加載父組件數據,進行業務操作
<template><!-- 子組件son2 --><div @click="bortherMethods"><!-- 父組件傳值展示 -->{{dataFromFather}}</div>
</template><script>
export default {data() {return {}},props: ['dataFromFather'],methods: {// 兄弟組件中的按鈕事件bortherMethods() {// 子組件事件方法...},}
}
</script><style lang="less" scoped>
/* .... */
</style>
子組件二:
組件功能解析: 加載父組件數據,通過click事件emit傳給父組件
<template><!-- 子組件son2 --><div @click="triggerBrotherMethods"><!-- 父組件傳值展示 -->{{dataFromFather}}</div>
</template><script>
export default {data() {return {}},props: ['dataFromFather'],methods: {// 觸發兄弟組件中的按鈕事件triggerBrotherMethods() {this.$emit('clickBrotherBtn', true)},}
}
</script><style lang="less" scoped>
/* .... */
</style>