##1.安装vuex
npm install vuex --save
使用npm安装并保存到package.json中
"devDependencies": {
"vuex": "^2.1.1",
},
##2.配置
配置方式和配置router(路由)差不多
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//创建Store实例
const store = new Vuex.Store({
// 存储状态值
state: {
...
},
// 状态值的改变方法,操作状态值
// 提交mutations是更改Vuex状态的唯一方法
mutations: {
...
},
// 在store中定义getters(可以认为是store的计算属性)。Getters接收state作为其第一个函数
getters: {
...
},
actions: {
...
}
})
// 要改变状态值只能通过提交mutations来完成
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App },
// 将store实例注入到根组件下的所有子组件中
store
// 子组件通过this.$store来方位store
})
##3.核心概念
###1. state
state就是全局的状态(数据源),我们可以用以下方式在Vue 组件中获得Vuex的state状态
template
<div>
{{ $store.state.count }}
</div>
script
console.log(this.$store.state.count)
###getters
getters其实可以认为是 store 的计算属性,用法和计算属性差不多。
定义getter:
getters: {
done(state) {
return state.count + 5;
},
}
使用getter
console.log(this.$store.getters.done)
###3.mutations
mutations是操作state的唯一方法,即只有mutations方法能够改变state状态值。
####3.1 基本操作
mutations对state的操作
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
组件通过commit提交mutations的方式来请求改变state
this.$store.commit('increment')
这样的好处是我们可以跟踪到每一次state的变化,以便及时分析和解决问题。
####3.2 提交载荷(Payload)
mutations方法中是可以传参的,具体用法如下:
mutations: {
// 提交载荷 Payload
add(state, n) {
state.count += n;
}
},
使用:
this.$store.commit('add', 10);
这里只是传了一个数字,在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读。
####3.3 注意
m
u
t
a
t
i
o
n
s
方
法
必
须
是
同
步
方
法
!
\color{red}{mutations方法必须是同步方法!}
mutations方法必须是同步方法!
##4. actions
###4.1 基本操作
之前说mutations方法必须只能是同步方法,为了处理异步方法,actions出现了。关于action和mutations的区别有以下几点
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
- Action 还是得通过 mutation 方法来修改state
同样是之前的increment方法,我们分别用同步和异步的action来验证上面所说的与mutations的不同之处:
actions: {
increment (context) {
context.commit('increment')
},
incrementAsync (context) {
// 延时1秒
setTimeout(() => {
context.commit('increment')
}, 1000)
}
},
不同于mutations使用commit方法,actions使用dispatch方法。
this.$store.dispatch('incrementAsync');
###4.2 context
context是与store实例具有相同方法和属性的对象。
可以通过context.state
和context.getters
来获取 state 和 getters。
###4.3 以载荷形式分发
incrementAsyncWithValue (context, value) {
setTimeout(() => {
context.commit('add', value)
}, 1000)
}
使用:
this.$store.dispatch('incrementAsyncWithValue', 5);
##5. module
使用单一状态树,导致应用的所有状态集中到一个很大的对象。但是,当应用变得很大时,store 对象会变得臃肿不堪。
为了解决以上问题,Vuex 允许我们将 store 分割到模块(module)
。每个模块拥有自己的 state、mutation、action、getters、甚至是嵌套子模块——从上至下进行类似的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
module 更多相关https://vuex.vuejs.org/zh/guide/modules.html
引用 知乎 https://www.jianshu.com/p/d6f7e11f18af