Vue---兄弟组件通信(三种方式) vue bus
第一种:eventBus新建一个js文件, 我这里叫做 bus.js;文件内容:import Vue from 'vue';export default new Vue();然后在你需要触发的 组件中引入importbusfrom‘文件路径’执行:bus.$emit('触发名称', 传输的数据 )最后在你需要的通信的另一个组件中mounted生命周期钩子中执行如下:bus.$on('触发名称',
Vue.observable
import Vue from 'vue'
export const state = Vue.observable({
screenCars: {},
})
export const mutations = {
updateScreenCars (payload) {
state.screenCars = Object.assign({}, payload)
},
}
<template>
<div>
<el-button @click="toSave">保存</el-button>
</div>
</template>
<script>
import {state, mutations} from './store.js'
export default {
name: 'table_form',
computed: {
screenCars() {
return state.screenCars
},
},
methods: {
setTest: mutations.updateScreenCars ,
toSave () {
// 此处修改的方法会通知store.js里面的数据发生变化
this.setTest({a:1})
},
},
}
</script>
第一种:eventBus
新建一个js文件, 我这里叫做 bus.js;
文件内容:
import Vue from 'vue';
export default new Vue();
然后在你需要触发的 组件中引入 import bus from ‘文件路径’
执行:bus.$emit('触发名称', 传输的数据 )
最后在你需要的通信的另一个组件中 mounted生命周期钩子中执行如下:
bus.$on('触发名称', res => {
//写你需要的方法
})
mounted () {
bus.$on(‘testA’, this.testA)
},
使用store作为中间仓库
<template>
子组件2
<div>{{secondInfo}}</div>
</template>
<script>
import Store from './store'
export default {
name: 'second',
data() {
return {
this.secondInfo: null
}
},
created(){
Store.$on('fromFirst', (info) => {
this.secondInfo = info
})
}
}
</script>
<template>
<div @click='hanleClick'>子组件1</div>
</template>
<script>
import Store from './store'
export default {
name: 'first',
methods: {
handleClick() {
Store.$emit('fromFirst', '来自子组件1的传值')
}
}
}
</script>
第二种:直接在 main.js中 直接如下
然后其中一个兄弟组件 执行
this. r o o t . v m . root.vm. root.vm.emit(‘触发名称’, 传输的数据);
另一个兄弟组件中执行
this.
r
o
o
t
.
v
m
.
root.vm.
root.vm.on(‘触发名称’, 传输的数据);
Vue—兄弟组件通信(三种方式)
3
第三种:同样是直接在 main.js
注意:emit 和 on 中 第一参数 触发名称 必须相同,同时二者原理一致
同时,需要关闭该通信,尤其是接口调用的时候,关闭方法 this.**.$off(“通信名称”)
Vue—兄弟组件通信(三种方式)
更多推荐
所有评论(0)