Vue EventBus傳值踩坑之Vuex完美解決

問題

多個組件通訊問題

EventBus傳值,頻繁會致使接口重複調用javascript

我覺得eventBus是專門處理兄弟組件之間通訊的,可是實際上,eventBus是專門處理同一個路由下的複雜組件之間通訊的。
若是涉及誇路由的組件通訊。能夠考慮利用$route對象傳參或者Vuexvue

vuex完美解決

因爲涉及v-model,須要特殊處理:java

buggit

computed property "XXX" was assigned to but it has no setter

處理

componentgithub

computed: {
  ...mapGetters({
      nameFromStore: 'name'
  }),
  name: {
     get(){
       return this.nameFromStore
     },
     set(newName){
       return newName
     } 
  }
}

storevuex

export const store = new Vuex.Store({
   state:{
     name : "Stackoverflow"
   },
   getters: {
     name: (state) => {
       return state.name;
     }
   }
}

個人處理

component 頁面this

<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.jscode

const state = {
  checkStatus:false
}
const getters = {}
const actions = {}
const mutations = {
  setCheckStatus(state,payload){
    state.checkStatus = payload
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}

其餘 component頁面 實時監聽checkStatuscomponent

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

相關文章
相關標籤/搜索