State:用于维护所有引用层的状态,并确保应用中只有唯一的数据源
组件中可以直接使用$store.state.count(store已经被注册到实例中),也可以先用mapState辅助函数将其映射下来
Getter:维护由State派生的一些状态,这些状态随State状态的变化而变化,类似computed属性,会被缓存
组件中可以直接使用$store.getters.tenTimesCount,也可以先用mapGetters辅助函数将其映射下来
Mutation:提供修改State的方法
组件中可以直接使用$store.commit来提交mutation
Action:类似Mutation,但不能直接修改状态,只能通过提交mutation来修改,可以包含异步操作
组件中可以直接使用$store.dispatch来分发action
Module:允许将store分割成模块,每个模块拥有独立的State,Getter,Mutation,Action,模块之中还可以嵌套模块
示例:store/index.js
export default new Vuex.Store({ //创建仓库
state: {
count: 0,
total: 15,
},
getters: {
tenTimesCount(state) {
return state.count * 10;
}
},
mutations: {
addCount(state, num) {
state.count += num || 1;
}
},
actions: {
// context具有和store实例相同的属性和方法
// 可以通过context的state和getters中的值,或者提交mutation和分发其他的action
addCountAsync(context, num) {
setInterval(() => {
if (context.state.count < 200) {
context.commit('addCount', num || 100);
}
}, num || 100);
}
},
modules: {
counter,
}
})
其中注释的代码为另一种写法index.vue
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
export default {
name: 'Vuex',
props: {},
data() {
return {}
},
computed: {
...mapState(['count', 'total']),
...mapState('counter', {
counterCount: 'count'
}),
...mapGetters(['tenTimesCount']),
...mapGetters('counter',{
counterTenTimesCount: 'tenTimesCount'
}),
/*count() {
return this.$store.state.count;
}
tenTimesCount() {
return this.$store.getters.tenTimesCount
}*/
},
methods: {
...mapMutations(['addCount']),
...mapMutations({ //为mutation赋别名,注意冲突
increaseCount: 'addCount'
}),
...mapMutations('counter',{ //为mutation赋别名,注意冲突
increaseCounterCount: 'addCount'
}),
...mapActions(['addCountAsync']),
...mapActions({ //为action赋别名,注意冲突
increaseCountAsync: 'addCountAsync'
}),
...mapActions('counter',{ //为action赋别名,注意冲突
increaseCounterCountAsync: 'addCountAsync'
}),
/*addCount() {
this.$store.commit('addCount', 10)
},
addCountAsync(num) {
this.$store.dispatch('addCountAsync', num);
},*/
}
}