上篇文章中说了 state 和 getters,本篇文章就来说说 mutations 和 actions。
提交 mutations 是改变 state 的唯一方式,不能用异步操作。actions 通过分发 action 来提交 mutation,可包含异步操作,比如 xhr 。
mutations
声明 mutations:
// mutations.js
import vue from 'vue'
export default {
CHANGE_LAST_NAME(state, newLastName) {
state.lastName = newLastName
},
CHANGE_AGE(state, params) {
state.age = params.age + 5
},
// 新增一个属性
SET_REPOS(state, repos) {
// 给 state 新添加属性
vue.set(state, 'repoList', repos)
}
}
使用 mutations
- 通过
mapMutations
映射方法; - 在方法中 调用
this.$store.commit('mutaion')
; - 可以在 mutation 种给 state 新增状态(属性),新增的状态会响应到视图上。
<template>
<div class="store">
<p>基本信息:{
{this.info}}</p>
<input type="text" name="age" id="age" v-model="age" placeholder="请输入年纪" />
<button @click="changeAge">修改年纪</button>
<button @click="changeAge2">修改年纪2</button>
<p>年纪:{
{this.$store.state.age}}</p>