Vue EventBus传值踩坑之Vuex完美解决

47 篇文章 0 订阅

问题

多个组件通信问题

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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值