在文件夹src下新建文件夹stores,接着在stores目录下新建一个名为globalStore.js的文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment: (state) => {
      state.count += 1
    },
    decrement: (state) => {
      state.count -= 1
    }
  }
})

接下来,我们新建两个页面来访问这个store。

这是pages/index/main.vue的代码内容:(从store中获取count状态值并显示)

<template>
  <div class="container">
    <div>计数结果:{{count}}</div>
    <a href="/pages/test/main">进入count增减页面</a>
  </div>
</template>
<script>
import globalStore from "../../stores/globalStore";
export default {
  computed: {
    count() {
      return globalStore.state.count;
    }
  }
};
</script>
<style scoped>
</style>

这是pages/test/main.vue的代码内容:(调用increment和decrement两个mutations去更新count值)

<template>
  <div class="container">
    <button @click="countDecrement">-</button>
    <span>{{count}}</span>
    <button @click="countIncrement">+</button>
  </div>
</template>
<script>
import globalStore from "../../stores/globalStore";
export default {  
  computed: {
    count() {      
      return globalStore.state.count;
    }
  },
  methods: {
    countIncrement() {
      globalStore.commit("increment");
    },
    countDecrement() {
      globalStore.commit("decrement");
    }
  }
};
</script>
<style scoped>

</style>