兄弟组件调用方法

方法一:在组件一创建方法;父组件通过 r e f 调 用 组 件 一 中 事 件 ; 组 件 二 通 过 ref调用组件一中事件;组件二通过 refemit调用父组件事件

 // 组件一;调用方法
 bortherMethods() {
    console.log("调用组件一的方法")
   },
<template>
  <div>
   <!-- 子组件1 -->
   <son1 ref= "borther" ></son1>
   <!-- 子组件2 -->
   <son2 @clickBrotherBtn= "triggerBrotherMethods"></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.bortherMethods()
   },
  }
}
</script>


 // 组件二;触发兄弟组件中的按钮事件
   @click= "triggerBrotherMethods"
 
   triggerBrotherMethods() {
    this.$emit( 'clickBrotherBtn')
   },

方法二:使用bus中间事件

import Vue from 'vue'
export default new Vue();
  //引入
import Bus from '@/utils/bus.js'
   Bus.$off('getCwbxList'); //先解绑,不然会多次触发
   //监听
   Bus.$on('getCwbxList',()=>{
     this.getList();
 })

//引入`在这里插入代码片`
import Bus from '@/utils/bus.js'
 this.$nextTick(function () {
    // DOM 现在更新了
    //触发方法;调用方法
 Bus.$emit('getCwbxList')
 })
bus.$on('getCwbxList', this.getMsg) 就相当于在watch里监听这个方法,
bus.$emit('getCwbxList')就会去触发这个监听;
bus.$on('getCwbxList', this.getMsg)写在哪里都行,不过一般是写在mounted里
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐