一、state

1、保存数据

仓库中保存数据:

  1. export default new Vuex.Store({
  2. state: {
  3. num: 0
  4. }
  5. })

2、访问数据

组件中获取数据:

  1. <template>
  2. <div>
  3. <h1>直接从仓库获取: {{ $store.state.num }}</h1>
  4. <h1>通过 computed 获取: {{ computedNum }}</h1>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. computed: {
  10. computedNum() {
  11. return this.$store.state.num;
  12. }
  13. }
  14. }
  15. </script>

我们可以直接获取仓库数据并使用,也可以用计算属性获取仓库数据,然后使用计算属性。

二、mutations

1、设置方法

设置仓库中的 mutations 方法:

  1. export default new Vuex.Store({
  2. state: {
  3. num: 1
  4. },
  5. getters: {
  6. },
  7. mutations: {
  8. INCREMENT(state) {
  9. state.num++;
  10. },
  11. DECREMENT(state) {
  12. state.num--;
  13. }
  14. }
  15. })

说明:mutations 中的方法名并不一定非要用纯大写,可根据自己的习惯来。

2、调用方法

组件中调用仓库 mutations 的方法:

  1. <template>
  2. <div>
  3. <h1>直接从仓库获取: {{ $store.state.num }}</h1>
  4. <h1>通过 computed 获取: {{ computedNum }}</h1>
  5. <button @click="$store.commit('DECREMENT')">-1</button>
  6. <button @click="increment">+1</button>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. computed: {
  12. computedNum() {
  13. return this.$store.state.num;
  14. }
  15. },
  16. methods: {
  17. increment() {
  18. this.$store.commit('INCREMENT');
  19. }
  20. }
  21. }
  22. </script>