vuex入门
vuex 的创建和基本属性和触发发方法
注意看注释 关键属性modules
state
getters
mutations
actions
const store = new Vuex.Store({ modules: { someModaule1: { // 模块1 namespaced: true, state: { // 状态 count: 0 }, getters: { // getters,会缓存属性 getCount: (state, getters) => { return state.someMOdaule1.count + getters.length } }, actions: { // 动作 ,支持异步,结果还是要触发 Mutation, 通过 store.dispatch('someModaule1/increment')触发 increment (context,arg) { console.log(arg) context.commit('increment') } }, mutations: { // Mutation必须为同步函数,去改变state, store.commit('someMOdaule1/increment', 10) increment (state, n) { state.count += n } }, modules: { // 嵌套模块 someModaule1: { // 继承父模块的命名空间 state: { ... }, getters: { profile () { ... } // -> getters['someModaule1/someModaule1'] } }, } }, someModauleOther: {...} // 其他模块 } })
调用
store.dispatch('someModaule1/increment') // 触发action store.commit('someMOdaule1/increment', 10) // 触发mutations
在组件中使用
大型项目通常用如下方法mapState()
mapGetters()
mapActions()
mapMutations()
Vue.use(Vuex) const Counter = { template: `<div>{{ count }}</div>`, store:store, // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 computed: { computed: { ...mapState('someModaule1', { 'count', // 传字符串参数 'count' 等同于 `state => state.count` 映射 this.count 为 store.someModaule1.state.count }), ...mapGetters('someModaule1',[ 'getCount', ]) }, }, methods: { ...mapActions('someModaule1',[ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('someModaule1/increment')` ]), ...mapMutations([ 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` ]) } }
mapState和其他map快捷方法接受的类型挺多要注意
- {} 重新命名相应的属性和方法,如果不重命名建议用下面的数组简写
- [string] 字符串简写,见上面注释
- string,[string] 加命名空间的,字符串简写
相关推荐
CSCCockroach 2020-09-15
lbPro0 2020-07-05
MrSunOcean 2020-06-21
lylwanan 2020-06-14
Callmesmallpure 2020-05-31
ShaLiWa 2020-05-25
墨龙吟 2020-04-24
MrSunOcean 2020-04-24
H女王范儿 2020-04-22
lbPro0 2020-04-16
ShaLiWa 2020-02-29
ShaLiWa 2020-01-17
MrSunOcean 2020-01-03
lbPro0 2020-01-01
H女王范儿 2019-12-29