一, 什么是 vuex?
官方解释: Vuex 是一个专为 vue.js 应用程序开发的状态管理模式
当项目比较庞大的时候, 每个组件的状态比较多, 为了方便管理, 需要把组件中的状态抽取出来, 放入 Vuex 中进行统一管理.
当我们需要构建一个中大型的单页面应用程序是, Vuex 可以更好的帮助我们在组件外部统一管理状态.
二, Vuex 的核心概念
1. 5 个核心概念
State
唯一的数据源: 我们需要把任何一个组件中需要抽取出来的变量放入到 state 中去
只要把 store 注册到 App.JS 中, 所有组件都可以使用其中的状态
- const Counter = {
- template: `<p>{{total}}</p>`,
- computed: {
- total(){
- return this.$store.state.total
- }
- }
- }
- Getters
通过 Getters 可以派生出一些新的状态
- // 创建一个 Vuex 的实例
- const store = new Vuex.Store({
- state: {
- goods: [
- {id: 1, name: '....', show: true},
- {id: 2, name: '....', show: false},
- .......
- ]
- },
- getters: {
- showGoods: state => {
- return state.goods.filter(good => good.show);
- }
- }
- });
- Mutations
更改 Vuex 的 store 中的状态的唯一方法时提交 mutation
- const store = new Vuex.Store({
- state: {
- total: 1
- },
- mutations: {
- add (state){
- // 更改状态
- state.total++;
- }
- }
- });
- // 调用:
- store.commit('add');
- Actions
Action 提交的是 mutation, 而不是直接变更状态,
Action 可以包含任何的异步操作, 但 mutation 必须是同步操作, 即所有的异步操作都写在 Action 里
- const store = new Vuex.Store({
- state: {
- total: 0
- },
- mutations: {
- add (state){
- // 更改状态
- state.total++;
- }
- },
- actions: {
- add(context){
- context.commit('add');
- }
- }
- });
- Modules
面对复杂的应用程序, 当管理的状态比较多时, 我们需要将 Vuex 的 store 对象分割成多个模块 (modules)
- const moduleA = {
- state: { ... },
- mutations: { ... },
- actions: { ... },
- getters: { ... }
- }
- const moduleB = {
- state: { ... },
- mutations: { ... },
- actions: { ... },
- getters: { ... }
- }
- const store = new Vuex.Store({
- modules: {
- a: moduleA,
- b: moduleB
- }
- });
2. Vuex 的运行逻辑
即 多个组件共享状态 时:
多个视图依赖于同一状态.
来自不同视图的行为需要变更同一状态.
传参的方法对于多层嵌套的组件将会非常繁琐, 并且对于兄弟组件间的状态传递无能为力, 采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝, 模式脆弱, 导致代码难以维护.
所以, Vuex 就是把组件的共享状态抽取出来, 以一个全局单例模式管理. 在这种模式下, 我们的组件树构成了一个巨大的 "视图", 不管在树的哪个位置, 任何组件都能获取状态或者触发行为!
另外, 通过定义和隔离状态管理中的各种概念并强制遵守一定的规则, 我们的代码将会变得更结构
以上是官网的截图, 下面这个是自己画的
操作步骤: 当组件中的状态发生改变, 通过 dispatch 函数提交到 Action,Actions 再通过 Commit 函数提交到 Mutations, 此时, 状态发生改变都会实时的去渲染组件.
什么情况下使用 Vuex?
来源: http://www.bubuko.com/infodetail-2987907.html