VueX中的核心内容
- state 存放状态
- mutations state成员操作
- getters 加工state成员给外界
- actions 异步操作
- modules 模块化状态管理
1: State
state 看作是所有组件的data, 用于保存所有组件的公共数据.
//vuex
state:{
products: []
},
//vue组件
this.$store.state.products //获取store中state的数据
// 使用mapState映射
import { mapState } from 'vuex'
computed: {
...mapState({
// mapState默认会把state当第一个参数传进来
getCount: state => state.count,
getSchool(state) {
return (val) => {
return state.school + val + this.date
}
}
})
},
2: Getters
可理解为所有组件的computed属性, 也就是计算属性
getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
//vuex
saleProducts: (state) => { return i; })
// 接受外部传参后处理的值(在通过方法访问时,每次都会去进行调用,而不会缓存结果)
getParam(state) {
return (param) => {
return state.school + param
}
}
//vue组件
this.$store.getters.saleProducts
this.$store.getters.getParam('param')
// 使用mapGetters映射
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'getGetters',
'getParam'
])
},
// 直接取值
console.log(this.$store.getters.getGetters)
console.log(this.getParam(this.date))
3: Mutations
mutaions理解为store中的methods, mutations对象中保存着更改数据的回调函数,该函数名官方规定叫type, 第一个参数是state, 第二参数是payload, 也就是自定义的参数.
//vuex
minusPrice (state, payload) {})
//vue组件
this.$store.commit('minusPrice', 666) //提交 minusPrice,payload为666
// 使用mapMutations映射
import { mapMutations } from 'vuex'
methods: {
...mapMutations({
handleStoreAdd: MT.ADD_COUNT,
handleStoreChange: MT.CHANGE
})
}
4: Actions
actions 类似于 mutations
不同在于:
actions提交的是mutations而不是直接变更状态
actions中可以包含异步操作, mutations中绝对不允许出现异步
actions中的回调函数的第一个参数是context, 是一个与store实例具有相同属性和方法的对象
//vuex
minusPriceAsync( context, payload ) {
setTimeout( () => {
context.commit( 'minusPrice', payload ); //context提交
}, 2000)
}
//vue组件
this.$store.dispatch('minusPriceAsync', 888); //分发actions中的minusPriceAsync这个异步函数
//使用mapActions映射
import { mapActions } from 'vuex'
methods: {
...mapActions([
'moduleFn'
])
}
5: Modules
Vuex 允许我们将 store 分割成模块(module)。
每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。
const moduleA = {
state: { a:1 },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { b:2 },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态