每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
下面我们就来开始总结vuex的几个属性,毫不客气的说,彻底的了解了这5个属性,VUEX也就学会了
一:基本属性
1. state:状态管理对象,直接放到vue的计算属性中即可
2. mutations:修改状态的唯一方式,通过commit('')的方式修改状态,只能执行同步操作,调用方式如下
1).this.$store.commit({
type: 'mutationName' //想要执行的mutation 方法名
amount:0 // 载荷参数
})
2). this.$store.commit('mutationName',{ amount:10})
3. getters:可以理解为计算属性,既然是计算属性,就有vue响应式的特点
4. actions:为了满足mutations中的异步操作,只能用dispatch('')调用,可以调用mutation函数
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
调用方式:
1).this.$store.dispatch({
type: 'actionName' //想要执行的actions 方法名
amount:0 // 载荷参数
})
2). this.$store.dispatch('actionName',{ amount:10})
5. modules:为了分担store的压力,每个module都可以有store的所有属性(state、modules、getters、mutaions、actions)等,难点可能在于命名空间,以后会讲解讲解
二: 快捷方式
mapGetters
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
mapState
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
map
Mutations
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
mapActions
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}
modules
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 的状态
未完待续...