关于javascript:Vue-EventBus传值踩坑之Vuex完美解决

41次阅读

共计 1416 个字符,预计需要花费 4 分钟才能阅读完成。

问题

多个组件通信问题

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 页面

<template>
  <div v-model="common.checkStatus">
    123
  </div>
</template>
<script>
import {mapState} from "vuex"
export default {
//component 页面 computed 局部
//computed
  computed: {
    ...mapState({
        common:state => state.common,
        checkStatus:state => state.common.checkStatus
    }),
  }
  //component 页面 watch 局部
  //watch 实时监听 checkStatus
  watch: {checkStatus(newVal){if(newVal){}else{}
    }
  }
}
</script>

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 完满解决

正文完
 0