首页 > 编程开发 > JavaScript    日期:2020-05-27 / 浏览

小计: 开发中遇到子组件需要调用兄弟组件中的方法,如下写个小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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章