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

问题

多个组件通信问题

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理