详解vuex使用方法

大兔子大兔子 提交于 2020-03-09 09:48:44

vuex有5个属性:State,Getter,Mutation,Action,Module

State:

1.可以直接使用 this.$store.state.count 获取
2.使用 mapState 获取:

import {mapState} from 'vuex'
export default {
  data() {
    return {
    };
  },
  computed:{
    ...mapState(['count'])
  }
};

Getter:

维护由State派生的一些状态,这些状态随State状态的变化而变化,与计算属性一样,Getter中的派生状态在被计算之后会被缓存起来,如果被依赖的状态没有发生改变时,就不会重新计算,直接用缓存值。

export default new Vuex.Store({
  state: {
    count: 1
  },
  getters:{
    addCount(state){
      return state.count + 10
    }
  }
})

在组件中获取:
1.直接使用 this.$store.getters.addCount 获取
2.使用 mapGetters 获取:

import {mapGetters} from 'vuex'
export default {
  data() {
    return {
    };
  },
  computed:{
    ...mapGetters(['addCount'])
  }
};

Mutation:

提供修改State的方法,mutation 必须同步执行

export default new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    addCount(state,num){
      state.count += num
    }
  }
})

在组件中使用:
1.直接使用 this.$store.commit(‘addCount’,10)
2.使用 mapMutations

<template>
  <div>
    <p>{{count}}</p>
    <button @click="addCount(10)">点击</button>
  </div>
</template>

<script>
import {mapState, mapMutations} from 'vuex'
export default {
  data() {
    return {
    };
  },
  computed:{
    ...mapState(['count'])
  },
  methods: {
     ...mapMutations(['addCount']),
  }
};
</script>

Action:

类似于Mutation,不同的是,Action不能直接修改状态,只能通过提交Mutation来修改。Action可以包含异步操作。可以commit多个mutations

export default new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    addCount(state,num){
      state.count += num
    },
  },
  actions: {
    addCountAsync(context){
      setTimeout(()=>{
        context.commit('addCount',10)
      },1000)
    }
  }
})

在组件中使用:
1.直接使用 this.$store.dispatch(‘addCountAsync’)
2.使用 mapActions

import {mapState, mapActions} from 'vuex'
export default {
  data() {
    return {
    };
  },
  computed:{
    ...mapState(['count'])
  },
  methods: {
    ...mapActions(['addCountAsync'])
  }
};

Module

官网解释:

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!