前提
有时候我们想要对修改状态进行异步操作,这时后可以使用actions
actions的使用
this.$store.dispatch('xxx', 参数)
index.js
state: {
userInfo: {
username: '张三',
userage: 8
},
},
mutations: {
updateUserage (state, newage) {
state.userInfo.userage = newage
}
},
actions: {
updateUserage2 (context, newage) {
setTimeout(() => {
context.commit('updateUserage', newage)
}, 1000)
}
}
渲染页面
<template>
<div>
<p>{{ $store.state.userInfo.userage }}</p>
<button @click="handleUpdate2(21)">延时1s更改年龄</button>
</div>
</template>
<script>
export default {
computed: {
},
methods: {
handleUpdate2 () {
this.$store.dispatch('updateUserage2', 20)
}
}
}
</script>
<style>
</style>
mapAction辅助函数的使用
<template>
<div>
<p>{{ $store.state.userInfo.userage }}</p>
<button @click="updateUserage2(21)">延时1s更改年龄</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
computed: {
},
methods: {
...mapActions(['updateUserage2']),
}
}
</script>
<style>
</style>