vue的vuex解析(二)之State、Mutations、Actions、Getters

State:

1、官网解释其为单一状态树,用一个对象就包含了全部的应用层级状态。
其实就是所有需要共享的数据的根节点,它里面包含了需要共享的数据,就是一个数据集合。
可以在vuex文件夹里独立创建一个state.js文件,并在该文件里面编写代码:
const state = {
count: 100000000,
};

export default state

2、将state.js引入store.js文件里面:
import state from ‘@/vuex/state’;
再在export default new Vuex.Store({})里面引入state:
export default new Vuex.Store({
state,
})

3、组件中就可以通过this.$store.state.count取得state中的count属性的值

4、mapState的使用:

mapState是获取state中的属性的值的辅助函数,如果你不想写成this.$store.state.count,
则可以在组件的computed中使用mapState,代码如下:
computed: {
mapState([‘count’]),
// 也可以写成,其中Count是count在组件中的别名
/*
mapState({
Count: ‘count’,
}),
*/
}

Mutations

1、mutations是用于直接更改state里面的属性的值,是同步修改,可以在vuex文件夹里面新建mutations.js文件,并在该文件里面编写:
const mutations = {
// state的count自增
increase(state) {
state.count++;
}
}

export default mutations
2、同State的步骤2
3、组件中通过this.$store.commit(‘increase’)来触发更改state的count的值

4、mapMutations的使用:

mapMutations是直接修改state中的属性的值的辅助函数,如果你不想写成this.$store.commit(‘increase’),
则可以在组件的methods中使用mapMutations,代码如下:
methods: {
mapMutations([‘increase’]),
// 也可以写成,其中Increase是increase在组件中的别名
/*
mapState({
Increase: ‘increase’,
}),
*/
// 用于触发mapAction获得的increase_actions
increaseClick() {
this.increase();
// 取别名时则写成
// this.Increase();
}
}

Actions

1、actions是用于间接修改state里面的属性的值,它是异步修改,可以在vuex文件夹里面新建actions.js文件,并在该文件里面编写:
const actions = {
// 提交mutations的increase方法实现修改state的count,它必须通过mutations才能修改state的count属性的值
increase_actions(context) {
context.commit(‘increase’);
}
}

export default actions
2、同State的步骤2
3、组件中通过this.$store.dispatch(‘increase_actions’)来触发间接更改state的count的值

4、mapActions的使用:

mapActions是间接修改state中的属性的值的辅助函数,如果你不想写成this.$store.dispatch(‘increase_actions’),
则可以在组件的methods中使用mapActions,代码如下:
methods: {
mapActions([‘increase_actions’]),
// 也可以写成,其中Increase_Actions是increase_actions在组件中的别名
/*
mapActions({
Increase_Actions: ‘increase_actions’,
}),
*/
// 用于触发mapAction获得的increase_actions
increaseActionsClick() {
this.increase_actions();
// 取别名时则写成
// this.Increase_Actions();
}
}

Getters

1、getters适用于筛选state的object类型数据满足某个条件的数据,例如state里面存在这种类型的object:
const state = {
list: [
{
id: 1,
flag: true,
name: ‘我是1’,
},
{
id: 2,
flag: false,
name: ‘我是2’,
},
{
id: 3,
flag: true,
name: ‘我是3’,
}
],
};则可以通过getters筛选出flag为true的数据
可以在vuex文件夹里面新建getters.js文件,并在该文件里面编写:
const getters= {
getToDoList(state) {
return state.list.filter((item) => item.flag == true);
}
}

export default getters
3、在组件里可以用this.$store.getters.getToDoList()获取state里面的list属性满足筛选条件的结果

4、mapGetters的使用:

mapGetters是筛选出state的list属性中满足条件的数据的辅助函数,倘若你不想使用this.$store.getters.getToDoList(),则可以在组件的computed中编写代码:
computed: {
mapGetters([‘getToDoList’]),
// 也可以写成,其中getGettersToDoList是getToDoList在组件中的别名
/*
mapGetters({
getGettersToDoList: ‘getToDoList’,
}),
*/
}

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值