Mutation不能异步,要用Action替代
修改state一定是通过Mutation进行
通过Action更改Mutation
store.dispatch(Mutation方法,数据)
Mutation修改state
state.js
export default {
userStatus: '', // 0 普通, 1 VIP, 2 高级VIP
vipLevel: ''
}
mutations.js
export default {
setMemberInfo (state, v) {
state.userStatus = v.userStatus
state.vipLevel = v.vipLevel
}
}
actions.js
export default {
buyVip ({ commit }, e) {
// 假装异步交互
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('setMemberInfo', { // 调用mutations,修改本地state
userStatus: e.userStatus,
vipLevel: e.vipLevel
})
resolve('购买成功') // 调用成功
}, 1000)
})
}
}
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import getters from './getters'
import actions from './actions'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
mutations,
actions
})
export default store
调用actions
buy.vue
<div class="abc"
v-for="(item,index) of list"
:key="index"
@click="buy(item)">
{{index}}
</div>
data () {
return {
list: [
{
userStatus: 2,
vipLevel: 2
},
{
userStatus: 2,
vipLevel: 3
}
]
}
},
buy: function (e) {
console.log(e) // 可以拿到数据
// 调用actions
this.$store.dispatch('buyVip', e).then(res => {
alert(res)
this.$router.push('/') // 跳首页
})
}