Vuex的store状态的更新唯一方式:提交Mutation
mutations主要包括:
- 字符串的事件类型(type)
- 一个回调函数,该回调函数的第一个参数就是state
在通过mutation更新数据的时候,有可能希望携带一些额外的参数,参数被称为是mutation的payload
- 但是如果参数不是一个的话。通常让
payload以对象的形式传递
vue
<template>
<div id="app">
<h2>{{$store.state.counter}}</h2>
<button @click="addition">+</button>
<!-- @click="{{$store.state.counter}}"这样写的话会影响其他界面 -->
<button @click="subtraction">-</button>
<button @click="addCount(10)">+10</button>
<hr />
<h4>getters-----计算平方</h4>
<h2>{{$store.state.counter}}</h2>
<h4>{{$store.getters.powerCounter}}</h4>
<hr />
<h4>超过20的学生:</h4>
<h4>{{$store.getters.more20Stu}}</h4>
<hr />
<h4>超过20的学生人数:</h4>
<h4>{{$store.getters.more20StuNum}}</h4>
<hr />
<h4>使用函数动态决定大于多少岁</h4>
<h4>{{$store.getters.moreAge(17)}}</h4>
<hr />
<h4>添加学生</h4>
<button @click="addStu">添加学生</button>
<h4>{{$store.state.students}}</h4>
</div>
</template>
<script>
export default {
components: {
},
methods: {
//store的mutations定义的方法
addition() {
this.$store.commit('increment')
},
subtraction() {
this.$store.commit('decrement')
},
addCount(count) {
this.$store.commit('incrementCount', count) //+10
},
addStu() {
const s = {name:'mary',age:22}
this.$store.commit('addStu', s)
}
},
}
</script>
<style>
</style>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
counter:4,
students:[
{ name:'lily',age:18 },
{ name:'rose',age:22 },
{ name:'jack',age:17 }, //增加学生对象使用push
]
},
//同步
mutations: {
//方法
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
},
incrementCount(state,count) {
state.counter += count //+10
},
addStu(state,s) {
state.students.push(s)
}
},
actions: {
},
modules: {
},
getters: {
powerCounter(state) {
return state.counter * state.counter
},
more20Stu(state) {
return state.students.filter(s => s.age > 18)
},
more20StuNum(state,getters) {
return getters.more20Stu.length
},
moreAge(state) {
return age => {
return state.students.filter(s => s.age > age)
}
},
}
})
- 上面是使用commit提交。除此之外还可以使用
type
,但是type需要将参数定义成payload,然后从中取出传入的参数。