Vue 3.0 中最新的 Vuex 方案在 v4.0.0-rc.1 版本,不过文档还是保持了更新状态。

安装

使用 yarn 安装最新的 vuex 版本

  1. yarn add vuex@next

使用

createStore

Vuex 4 版本中提供 createStore 函数来创建 store。新建 store.js 文件

  1. import { createStore } from 'vuex'
  2. const store = createStore({
  3. state: {
  4. count: 0
  5. },
  6. mutations: {
  7. increment(state, count){
  8. state.count = count
  9. }
  10. },
  11. actions: {
  12. Increment({commit, state}) {
  13. state.count++
  14. commit('increment', state.count)
  15. }
  16. }
  17. })
  18. export default store;

我们可以发现其实写法和以前没什么差别。在 main.js 中 use 状态

  1. import { createApp } from 'vue'
  2. import Store from './components/Store.vue'
  3. import store from './store.js'
  4. createApp(Store)
  5. .use(store)
  6. .mount('#app')

useStore

由于在 Vue 3.0 中没有 this 概念,所以 Vuex 提供了 useStore 在 setup 函数中访问,它的对象其实和以前的 this.$store 没有差别

  1. <template>
  2. <h3>Vuex 状态</h3>
  3. <div>{{count}}</div>
  4. <button @click="add">累加</button>
  5. </template>
  6. <script>
  7. import { computed, defineComponent } from 'vue'
  8. import { useStore } from 'vuex'
  9. export default defineComponent({
  10. setup() {
  11. const store = useStore()
  12. return {
  13. count: computed(() => store.state.count),
  14. add: () => store.dispatch('Increment')
  15. }
  16. }
  17. })
  18. </script>

需要注意的是我们不能直接通过赋值得到一个响应式的 count,而需要使用 Vue 3.0 的计算属性 computed 代理才可以

  1. // bad
  2. const count = store.state.count
  3. // good
  4. const count = computed(() => store.state.count)