Vuex 是一个用于管理 Vue.js 应用中的状态的状态管理库。它包含了五个核心属性和一些基本的使用方法:
本文文章目录
1. state: `state` 是应用中的数据源,类似于组件中的 `data`。它是一个响应式对象,可以在组件中访问。在 Vuex 中,应该尽量将组件的共享状态存储在 `state` 中。
const store = new Vuex.Store({ state: { count: 0 } })
2. mutations: `mutations` 用于修改 `state` 中的数据。它们必须是同步函数,用于执行状态的变更操作。通过提交(mutating)一个 mutation 来改变状态。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } })
3. getters: `getters` 允许你在访问 `state` 数据时进行计算或者过滤操作。它类似于计算属性。
const store = new Vuex.Store({ state: { todos: [...] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
4. actions: `actions` 用于处理异步操作,可以包含任意异步操作,然后再提交 mutations 来修改 `state`。它可以用于处理数据获取、异步 API 请求等。
const store = new Vuex.Store({ state: { ... }, mutations: { ... }, actions: { fetchData(context) { // 异步操作,然后提交 mutation axios.get('/data').then(response => { context.commit('setData', response.data) }) } } })
5. modules: `modules` 允许将 Vuex 分割成多个模块。每个模块有自己的 `state`、`mutations`、`getters` 和 `actions`。这可以帮助管理大型应用的状态。
const store = new Vuex.Store({ modules: { moduleA: { state: { ... }, mutations: { ... }, actions: { ... } }, moduleB: { state: { ... }, mutations: { ... }, actions: { ... } } } })
使用 Vuex 时,你需要在 Vue 组件中通过 `$store` 访问这些属性,如 `$store.state`、`$store.commit`、`$store.dispatch` 和 `$store.getters`。通过这些属性和方法,你可以实现全局状态管理和响应式数据流动。
总结: