zoukankan      html  css  js  c++  java
  • vuex在vue3中使用mutation/actions/state/getters的几种形式说明

    补充:vuex在vue3中使用mutation/actions/state/getters的几种形式说明*

    1.在template直接使用,$store在template中不能识别会飘红但是不影响使用,去掉飘红在d.ts的文件中加上declare const $store:any

    2.非辅助函数方式

    state 在setup放回的函数中通过key:computed(()=>store.state.值) --->在module中 key:computed(()=>store.state.moduleName[stateName])

    getters key:computed(()=>store.getters.值)--->在module中 key:computed(()=>store.getters['moduleName/getterName'])*

    mutation key: ()=>{store.commit('mutationMethodName')}--->在module中 key:()=>{store.commit('moduleName/mutationMethodName')}*

    actions key: ()=>{store.dispatch('actionMethodName')}--->在module中 key:()=>{store.dispatch('moduleName/actionMethodName')}*

    3.辅助函数方式

    注意:测试在vue3中mapState跟mapGetters在setup函数返回的对象结构出来的state跟getters是函数,这个函数应该放在computed函数中,其返回值才是我们真正想获取到的响应式的值。特别注意的是这个函数我们在当作参数传递给computed时,我们要显示的为这个函数绑定this为 {$store:store} ;mapMutations跟mapActions在setup直接返回可以在template正常使用*

    import {
    
      mapState as mapRootState,
    
      useStore,
    
      mapGetters as mapRootGetters,
    
      createNamespacedHelpers,
    
    } from 'vuex';
    
    import { computed } from 'vue';
    
    export const useState = (*mapper*: string[], *moduleName*?: string) => {
    
      const store = useStore();
    
      let mapFns: Record<string, any>;
    
      const state: Record<string, any> = {};
    
      let mapState;
    
      if (*moduleName*) {
    
    ​    mapState = createNamespacedHelpers(*moduleName*).mapState;
    
      } else {
    
    ​    mapState = mapRootState;
    
      }
    
      mapFns = mapState(*mapper*);
    
      Object.keys(mapFns).forEach(*fnKey* => {
    
    ​    state[*fnKey*] = computed(mapFns[*fnKey*].bind({ $store: store }));
    
      });
    
      return state;
    
    };
    
    
    
    export const useGetters = (*mapper*: string[], *moduleName*?: string) => {
    
      const store = useStore();
    
      let mapFn: Record<string, any>;
    
      const getters: Record<string, any> = {};
    
      let mapGetters;
    
      if (*moduleName*) {
    
    ​    mapGetters = createNamespacedHelpers(*moduleName*).mapGetters;
    
      } else {
    
    ​    mapGetters = mapRootGetters;
    
      }
    
      mapFn = mapGetters(mapper);
    
      Object.keys(mapFn).forEach(*key* => {
    
    ​    getters[*key*] = computed(mapFn[*key*].bind({ $store: store }));
    
      });
    
      return getters;
    
    };
    
  • 相关阅读:
    ibmmq 性能测试
    zabbix-agent 安装
    关于dubbo接口性能测试
    关于vyos 防火墙配置
    appium自动化的工作原理(1)
    unittest如何在循环遍历一条用例时生成多个测试结果
    在Linux中#!/usr/bin/python之后把后面的代码当成程序来执行。 但是在windows中用IDLE编程的话#后面的都是注释,之后的代码都被当成文本了。 该怎么样才能解决这个问题呢?
    Cookie和Session的区别详解
    点单登录原理和java实现简单的单点登录
    new一个JAVA对象的时候,内存是怎么分配的?
  • 原文地址:https://www.cnblogs.com/comyan/p/15291253.html
Copyright © 2011-2022 走看看