zoukankan      html  css  js  c++  java
  • 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完美解决

  • 相关阅读:
    java学习笔记—ServletConfig、ServletContext接口(13)
    php中的XML DOM(11)
    php中的XML DOM(10)
    java学习笔记—Servlet技术(11)
    MM-移动类型
    MM-委外业务
    English-商务英文邮件例句100句
    ABAP-表中数据的横向累加
    MM-实际应用中的难题
    ABAP-加密解密
  • 原文地址:https://www.cnblogs.com/yihan123/p/13675021.html
Copyright © 2011-2022 走看看