Vuex 背后的基本思想: 把组件的共享状态抽取出来,以一个全局单例模式管理,在这种模式下,咱们的组件树构成了一个巨大的“视图”,无论在树的哪一个位置,任何组件都能获取状态或者触发行为!javascript
另外,经过定义和隔离状态管理中的各类概念并强制遵照必定的规则,咱们的代码将会变得更结构化且易维护。css
特色: html
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地获得高效更新。vue
你不能直接改变 store 中的状态。改变 store 中的状态的惟一途径就是显式地提交 (commit) mutation。这样使得咱们能够方便地跟踪每个状态的变化,从而让咱们可以实现一些工具帮助咱们更好地了解咱们的应用java
在 Vue 的单页面应用中使用,须要使用Vue.use(Vuex)
调用插件。
使用很是简单,只须要将其注入到Vue根实例中。vuex
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 能够包含异步操做
// context 是一个与 store 实例具备相同方法和属性的 context 对象
}
}
})
// 注入到根实例
new Vue({
el: '#app',
store,
template: '<App/>',
components: { App }
})复制代码
而后改变状态:数组
this.$store.commit('increment')复制代码
Vuex 主要有四部分:promise
store
中存储的各个状态。store
中状态的执行者。Vuex 使用 state
来存储应用中须要共享的状态。为了能让 Vue 组件在 state
更改后也随着更改,须要基于state
建立计算属性。bash
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count // count 为某个状态
}
}
}复制代码
相似于 Vue 中的 计算属性,能够在因此来的其余 state
或者 getter
改变后自动改变。
每一个getter
方法接受 state
和其余getters
做为前两个参数app
getters: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
}复制代码
前面两个都是状态值自己,mutations
才是改变状态的执行者。mutations
用于同步地更改状态
// ...
mutations: {
increment (state, n) {
state.count += n
}
}复制代码
其中,第一个参数是state
,后面的其余参数是发起mutation
时传入的参数。
this.$store.commit('increment', 10)复制代码
commit
方法的第一个参数是要发起的mutation
名称,后面的参数均当作额外数据传入mutation
定义的方法中。
规范的发起mutation
的方式以下:
store.commit({
type: 'increment',
amount: 10 //这是额外的参数
})复制代码
额外的参数会封装进一个对象,做为第二个参数传入mutation
定义的方法中。
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}复制代码
想要异步地更改状态,须要使用action
。action
并不直接改变state
,而是发起mutation
。
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}复制代码
发起action
的方法形式和发起mutation
同样,只是换了个名字dispatch
。
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})复制代码
想要使用action
处理异步工做很简单,只须要将异步操做放到action
中执行(如上面代码中的setTimeout
)。
要想在异步操做完成后继续进行相应的流程操做,有两种方式:
action
返回一个 promise
。dispatch
方法的本质也就是返回相应的action
的执行结果。因此dispatch
也返回一个promise
。store.dispatch('actionA').then(() => {
// ...
})
复制代码
async/await
。代码更加简洁。// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}复制代码
将state
和getter
结合进组件须要使用计算属性:
computed: {
count () {
return this.$store.state.count
// 或者 return this.$store.getter.count2
}
}
复制代码
将mutation
和action
结合进组件须要在methods
中调用this.$store.commit()
或者this.$store.commit()
:
methods: {
changeDate () {
this.$store.commit('change');
},
changeDateAsync () {
this.$store.commit('changeAsync');
}
}复制代码
为了简便起见,Vuex 提供了四个方法用来方便的将这些功能结合进组件。
mapState
mapGetters
mapMutations
mapActions
示例代码:
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
// ....
computed: {
localComputed () { /* ... */ },
...mapState({
// 为了可以使用 `this` 获取局部状态,必须使用常规函数
count(state) {
return state.count + this.localCount
}
}),
...mapGetters({
getterCount(state, getters) {
return state.count + this.localCount
}
})
}
methods: {
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为`this.$store.commit('increment')`
}),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
复制代码
若是结合进组件以后不想改变名字,能够直接使用数组的方式。
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
}复制代码
能够将应用的store
分割为小模块,每一个模块也都拥有全部的东西:state
, getters
, mutations
, actions
。
首先建立子模块的文件:
// initial state
const state = {
added: [],
checkoutStatus: null
}
// getters
const getters = {
checkoutStatus: state => state.checkoutStatus
}
// actions
const actions = {
checkout ({ commit, state }, products) {
}
}
// mutations
const mutations = {
mutation1 (state, { id }) {
}
}
export default {
state,
getters,
actions,
mutations
}
复制代码
而后在总模块中引入:
import Vuex from 'vuex'
import products from './modules/products' //引入子模块
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
products // 添加进模块中
}
})
复制代码
其实还存在命名空间的概念,大型应用会使用。须要时查看文档便可。Vuex的基本使用大体如此。
参考
https://www.jianshu.com/p/aae7fee46c36
https://vuex.vuejs.org/zh/guide/modules.html