vue中子组件调用兄弟组件方法
2018-07-06 10:26
633 查看
小计: 开发中遇到子组件需要调用兄弟组件中的方法,如下写个小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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- Vue兄弟组件之间如何调用对方的方法
- vue 2.0 父组件调用子组件中的方法
- vue 父组件调用子组件方法及事件
- vue组件之间的通信以及如何在父组件中调用子组件的方法和属性
- vue 父组件调用子组件方法解决方案
- vue2.0 兄弟组件数据传递方法
- vue之子组件调用父组件的方法
- vue中子组件的methods中获取到props中的值方法
- vue 子组件调用父组件方法
- vue 子组件调用父组件的方法
- vue 使用ref 让父组件调用子组件的方法
- vue中父组件调用子组件的方法和属性
- vue.js组件之间通讯--父组件调用子组件的一些方法,子组件暴露一些方法,让父组件调用
- vue,父组件调用子组件方法
- vue 父组件调用子组件方法
- vue关于父组件调用子组件的方法
- Vue 兄弟组件通信的方法(不使用Vuex)
- vue组件之间的通信以及如何在父组件中调用子组件的方法和属性
- vue.js中父组件调用子组件的内部方法示例
- Vue $emit $refs子父组件间方法的调用实例