开始使用 Vuex

正如我们在上一节中提到的,所有 Vuex 活动都发生在一个 store 中,这个 store 可以简单地在你的项目根目录下创建。然而,虽然看起来很简单,但 Vuex store 与普通的 JavaScript 对象不同,因为它具有响应性,就像带有 v-model 指令的 <input> 元素的双向绑定一样。因此,当 store 中的 state 数据发生变化时,你在 Vue 组件中访问的任何 state 数据都会被响应式地更新。storestate 中的数据必须通过 mutations 显式地提交,就像我们在上一节的图表中解释的那样。

在本练习中,我们将使用单文件组件(SFC)的骨架来构建一些带有 Vuex 的简单 Vue 应用程序。我们将把所有的示例代码放在我们的 GitHub 仓库的 /chapter-10/vue/vuex-sfc/ 目录下。让我们开始吧。

安装 Vuex

在创建 Vuex store 之前,我们必须安装 Vuex 并导入它,步骤如下:

  1. 使用 npm 安装 Vuex

    $ npm i vuex
  2. 使用 Vue.use() 方法导入并注册它:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)

请记住,上述安装步骤旨在将 Vuex 与模块系统一起使用,这正是我们在本章的目标。但是在深入了解模块系统应用程序之前,我们应该在下一节中看看如何通过 CDN 或直接下载来创建 Vuex 应用程序。

请注意,Vuex 需要 Promise 支持。如果你的浏览器不支持 Promise,请查看 https://vuex.vuejs.org/installation.html#promise 以了解如何为你的应用程序安装 polyfill 库。

创建一个简单的 store

我们可以通过以下步骤,使用 CDN 或直接下载来启动一个简单的 store

  1. 使用 HTML <script> 块安装 VueVuex

    <script src="/path/to/vue.js"></script>
    <script src="/path/to/vuex.js"></script>
  2. HTML <body> 块中激活 Vuex store

    <script type="text/javascript">
    const store = new Vuex.Store({
      state: { count: 0 },
      mutations: {
        increment (state) {
          state.count++
        }
      }
    })
    
    store.commit('increment')
    console.log(store.state.count) // -> 1
    </script>

    你可以从这段代码中看到,你只需要在一个 JavaScript 对象中创建 Vuexstate,一个 mutation 方法,然后你就可以通过 storestate 键访问 state 对象,并通过 storecommit 方法触发 state 的更改,如下所示:

    store.commit('increment')
    console.log(store.state.count)

在这个简单的例子中,我们遵守了 Vuex 中强制规则之一,即通过提交 mutation 而不是直接更改来改变 state 数据。让我们在下一节中通过创建模块系统应用程序来深入了解 Vuex 的核心概念和其他规则。