vuex-getters
- getters是vuex中的一个属性,主要作用于vue中的计算属性(computed)类似,用来存放一些经过修改的数值
- getters的基本用法与mutations类似,都是一个函数,函数的参数默认为state
getters: {
power(state) {
return state.counter * state.counter;
}
- 在调用getters中的内容是使用 $store.getters.函数名进行调用
- 作为函数参数使用时,函数除了state参数以外,还可以将getters作为函数参数
age20Length(state, getters) {
return getters.age20.length;
}
- 但是如果想要在getters中输入自定义的数据时,无法直接添加参数,所以使用返回值为函数的getters来实现。例如:返回学生年龄大于20岁的所有学生信息
ageMore(state) {
return function (age) {
return state.student.filter(s => s.age > age);
}
}
//在组件中调用该函数时添加参数age
<p>{{$store.getters.ageMore(20)}}</p>
vuex-mutations
- 默认格式
increment(state) {
state.counter++;
}
- 可以为mutations添加参数,该参数被称作负载(payload)。为mutations添加参数时,需要在 **this.$store.commit()**函数中添加,之后将该参数传入mutations中的函数里
template模板
<button @click="addCount(5)">+5</button>
<button @click="addCount(10)">+10</button>
methods方法
addCount(count) {
this.$store.commit('addCount', count);
}
mutations属性
addCount(state, count) {
state.counter += count;
}
- 传入的参数不一定是一个参数,也可以是多个参数,在这种情况下传入的参数为对象类型
mutations提交方式
- vuex中mutations有两种提交风格,默认风格为:this.$store.commit(‘addCount’, count);
- 第二种提交风格为对象类型,格式如下
this.$store.commit({
type: 'addCount',
count
});
- 使用第二种提交风格时,需要对mutations中的特定函数进行修改。此时,参数count传入的不是用户输入的特定数据,而是整个对象被传入mutations中的函数中,对对象中的某个键进行修改,参数一般使用payload
addCount(state, payload) {
state.counter += payload.count;
}