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;
    
    };
    
  • 相关阅读:
    Hibernate Annotation (Hibernate 注解)
    org/objectweb/asm/Type异常解决办法
    Spring3 MVC 总结(转)
    Spring mvc 3 在controller和视图之间传递参数
    各种树tree的js控件优缺点
    Spring MVC 的请求参数获取的几种方法
    解决javax.persistence.OneToMany.orphanRemoval()Z异常办法
    ModelAndView返回自己的用法
    javax.persistence.Entity异常解决方法
    调用http://WebXml.com.cn/的webservice获取手机号段信息
  • 原文地址:https://www.cnblogs.com/comyan/p/15291253.html
Copyright © 2011-2022 走看看