Vue EventBus传值踩坑之Vuex完美解决
作者:易涵123
来源:SegmentFault 思否社区
问题
多个组件通信问题
EventBus传值,频繁会导致接口重复调用
我以为eventBus是专门处理兄弟组件之间通信的,但是实际上,eventBus是专门处理同一个路由下的复杂组件之间通信的。
如果涉及夸路由的组件通信。可以考虑利用$route对象传参或者Vuex
vuex完美解决
由于涉及v-model,需要特殊处理:
bug
computed property "XXX" was assigned to but it has no setter
处理
component
computed: {
...mapGetters({
nameFromStore: 'name'
}),
name: {
get(){
return this.nameFromStore
},
set(newName){
return newName
}
}
}
store
export const store = new Vuex.Store({
state:{
name : "Stackoverflow"
},
getters: {
name: (state) => {
return state.name;
}
}
}
我的处理
component 页面
123
store下的common.js
const state = {
checkStatus:false
}
const getters = {}
const actions = {}
const mutations = {
setCheckStatus(state,payload){
state.checkStatus = payload
}
}
export default {
state,
getters,
actions,
mutations
}
其他 component页面 实时监听checkStatus
import {mapState} from "vuex"
export default {
computed: {
...mapState({
checkStatus:state => state.common.checkStatus
}),
},
//watch 实时监听checkStatus
watch: {
checkStatus(newVal){
if(newVal){
}else{
}
}
}
}
其他 component页面 更新checkStatus
import {mapState} from "vuex"
export default {
methods:{
clickOpen(){
this.$store.commit("setCheckStatus",true)
},
clickClose(){
this.$store.commit("setCheckStatus",false)
}
}
}
Vue EventBus传值踩坑之Vuex完美解决:
https://github.com/yihan12/day-to-day/blob/master/202009/Vue%20EventBus%E4%BC%A0%E5%80%BC%E8%B8%A9%E5%9D%91%E4%B9%8BVuex%E5%AE%8C%E7%BE%8E%E8%A7%A3%E5%86%B3.md
评论