总结
mutations
- vuex 改变状态的唯一方法 mutations中的方法不能直接调用
- 写法
const store = new Vuex.Store({
state:{
user:{
name: '',
tel: '',
id: '',
sex: '男'
}
},
mutations: {
changeSex(state, userSex) {
state.user.sex = userSex
}
}
})
- 用法
第一种用法
<template>
<div>{{user.sex}}</div>
<button @click="fun">提交</button>
</template>
import { mapState } from 'vuex'
export default {
data() {
return {}
},
computed: {
...mapState([
'user'
])
},
methods:{
fun() {
this.$store.commit('changeSex', '女')
}
}
}
第二种用法
<template>
<div>{{user.sex}}</div>
<button @click="changeSex">提交</button>
</template>
import { mapState, mapMutations } from 'vuex'
export default {
data() {
return {}
},
computed: {
...mapState([
'user'
])
},
methods:{
...mapMutations([
'changeSex'
])
}
}