入门

每个 Vuex 应用程序的核心都是 **store**。一个“store”本质上是一个包含应用程序 **state** 的容器。有两件事使 Vuex store 不同于普通的全局对象

  1. Vuex store 是响应式的。当 Vue 组件从 store 中获取 state 时,如果 store 的 state 发生变化,它们将以响应式和高效的方式更新。

  2. 您不能直接修改 store 的 state。更改 store state 的唯一方法是显式地 **提交 mutation**。这确保了每次 state 更改都留下了可跟踪的记录,并使工具能够帮助我们更好地理解我们的应用程序。

最简单的商店

注意

在文档的其余部分,我们将使用 ES2015 语法作为代码示例。如果您还没有学习它,您应该学习

安装 Vuex 后,让我们创建一个 store。这非常简单 - 只需提供一个初始 state 对象和一些 mutation

import { createApp } from 'vue'
import { createStore } from 'vuex'

// Create a new store instance.
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

const app = createApp({ /* your root component */ })

// Install the store instance as a plugin
app.use(store)

现在,您可以将 state 对象作为 store.state 访问,并使用 store.commit 方法触发 state 更改

store.commit('increment')

console.log(store.state.count) // -> 1

在 Vue 组件中,您可以将 store 作为 this.$store 访问。现在我们可以使用组件方法提交 mutation

methods: {
  increment() {
    this.$store.commit('increment')
    console.log(this.$store.state.count)
  }
}

同样,我们提交 mutation 而不是直接更改 store.state.count 的原因是,我们希望显式地跟踪它。这种简单的约定使您的意图更加明确,以便您在阅读代码时能够更好地理解应用程序中的 state 更改。此外,这使我们有机会实现可以记录每个 mutation、获取 state 快照,甚至执行时间旅行调试的工具。

在组件中使用 store state 只需在计算属性中返回 state,因为 store state 是响应式的。触发更改只需在组件方法中提交 mutation。

接下来,我们将更详细地讨论每个核心概念,从State开始。