Vuex概念复习

Vuex概念复习

自己再度复习Vuex时的总结

核心概念

  • State 提供唯一公共数据源

  • https://vuex.vuejs.org/zh/guide/state.html

  • 调用1 this.$store.state.xxx

  • 调用2 使用辅助函数 mapState

    当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键

    import { mapState } from 'vuex'
    
    computed:{
        ...mapState(['count'])
    }
    
  • 修改数据方式只能通过mutation来变更 不能直接像this.$store.state.xxx ++这样去修改

  • mutation 变更数据,虽然麻烦但好监控

    • 在store里的mutations:里添加方法

        mutations: {
          countAdd(state,step=1) {
            state.count+=step
          },
          countSub(state,step=1) {
            state.count-=step
          }
        },
      
    • 调用1: this.$store.commit('countAdd')

      // <button @click="add(3)">++</button> <button @click="sub">--</button>
      methods: {
          add(step) {
            this.$store.commit('countAdd', step)
          },
          sub() {
            this.$store.commit('countSub')
          },
        },
      
    • 调用2: mapMutations 函数 ,就不用去methods新弄一个函数再去调用

      import { mapMutations } from 'vuex'
      
      export default {
        // ...
        methods: {
          ...mapMutations(['countPow']) 
       // 然后@clik="countPow" 就可以用了
        }
      }
      
    • 有异步的话改怎么办呢 要用Action

    • 使用v-model建议换成v-bind和@input等,间接修改state

  • Action类似于 mutation 大概就是在异步任务完成后间接调用mutations

    • 只有mutation才有修改数据的权力

    • 使用 在actions里的异步任务里写context.commit(func)

        actions: {
          countAddAsync(context) {
            setTimeout(() => {
              context.commit('countAdd')
            }, 1000)
          }
        },
      
    • 调用1 this.$store.dispatch('countAddAsync'),带参数跟mutation一样

    • 调用2 mapActions 使用跟mapMutitons差不多

  • Getter 对store里的数据进行加工处理形成新数据,类似于计算属性

      getters: {
        showCount(state) {
          return `当前count值${state.count}`;
        }
      },
    
    • 调用1 <h2>{{$store.getters.showCount}}</h2>

    • 调用2 mapGetters 使用跟mapMutitons差不多(放computed里)

  • module 数量多了,大模块分割成一个个模块来用

    • https://vuex.vuejs.org/zh/guide/modules.html

    • 有主模块(root),和一堆子模块

    • 同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState

    • 命名空间 的使用

      • :{{$store.state.user.xxx}}

      • methods:{
            ...mapMutations({
                'changexxx':'user/changeXXX',
                'xxxA':'user/cxxxA'
            })
        }
        // 不能直接[]的形式,要以对象的形式
        // 子模块要加 namespaced:true (别打错了)
        
      • action方法调用this.$store.dispatch('user/login',参数)

原文地址:https://www.cnblogs.com/somegenki/p/13443585.html