vue中子組件調用兄弟組件方法
小計: 開發(fā)中遇到子組件需要調用兄弟組件中的方法,如下寫個小demo記錄下心得,如果你有好的方法,請到評論區(qū)域指教
父組件示例代碼:
組件功能解析:
通過$emit獲取子組件事件,通過$ref調用子組件中事件,實現(xiàn)子組件二的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>
子組件一
組件功能解析:
加載父組件數(shù)據(jù),進行業(yè)務操作
<template> <!-- 子組件son2 --> <div @click="bortherMethods"> <!-- 父組件傳值展示 --> {{dataFromFather}} </div> </template> <script> export default { data() { return { } }, props: ['dataFromFather'], methods: { // 兄弟組件中的按鈕事件 bortherMethods() { // 子組件事件方法 ... }, } } </script> <style lang="less" scoped> /* .... */ </style>
子組件二:
組件功能解析:
加載父組件數(shù)據(jù),通過click事件emit傳給父組件
<template> <!-- 子組件son2 --> <div @click="triggerBrotherMethods"> <!-- 父組件傳值展示 --> {{dataFromFather}} </div> </template> <script> export default { data() { return { } }, props: ['dataFromFather'], methods: { // 觸發(fā)兄弟組件中的按鈕事件 triggerBrotherMethods() { this.$emit('clickBrotherBtn', true) }, } } </script> <style lang="less" scoped> /* .... */ </style>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue中改變了vuex數(shù)據(jù)視圖不更新,也監(jiān)聽不到的原因及解決
這篇文章主要介紹了vue中改變了vuex數(shù)據(jù)視圖不更新,也監(jiān)聽不到的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03Vue如何實現(xiàn)利用vuex永久儲存數(shù)據(jù)
這篇文章主要介紹了Vue如何實現(xiàn)利用vuex永久儲存數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04Element中table組件按照屬性執(zhí)行合并操作詳解
在我們日常開發(fā)中,表格業(yè)務基本是必不可少的,對于老手來說確實簡單,家常便飯罷了,但是對于新手小白如何最快上手搞定需求呢?本文從思路開始著手,幫你快速搞定表格2022-11-11Vue實現(xiàn)一個動態(tài)添加行的表格步驟詳解
在Vue組件中定義表格的數(shù)據(jù)模型,通常使用一個數(shù)組來存儲表格的數(shù)據(jù),每一行數(shù)據(jù)可以是一個對象,對象的屬性對應表格的列,這篇文章主要介紹了Vue實現(xiàn)一個動態(tài)添加行的表格步驟詳解,需要的朋友可以參考下2024-05-05