Vue-admin工作整理(十): Vuex-Actions(模拟接口请求实现组件字段更新)
思路:通过提交一个 mutation,而不是直接变更状态,它可以包括异步操作,通过请求接口,定义一个方法,第一个参数为对象,在里面能够提取到一些东西,比如:commit,这是一个方法,调用这个commit去提交一个mutation
import { getAppName } from '@/api/app' const actions = { // 请求接口,修改appName字段数据,定义一个updateAppName方法,第一个参数为对象,在里面能够提取到一些东西,比如:commit,这是一个方法, // 调用这个commit去提交一个mutation,“{ commit }”写法为es6的方式,它相当于获取到的是一个params对象。 // upadateAppName ({ commit }) { // // es6的函数 // getAppName().then(res => { // 模拟一个异步请求, // const { info: { appName } } = res // es6的写法 // commit('setAppName', appName) // }).catch(err => { // console.log(err) // }) async updateAppName ({ commit }) { // es8的回调函数 console.log({ commit }) try { const { info: { appName } } = await getAppName() commit('setAppName', appName) } catch (err) { console.log(err) } } } export default actions
<template>
<div>
<a-input v-model="inputValue"/>
<p>{{ inputValue }} -> lastLetter is {{ inputValueLastLetter }}</p>
<p>appName: {{ appName }} -> appNameWithVersion is {{ appNameWithVersion }}</p>
<p>userName: {{ userName }} -> firstLetter is {{ firstLetter }}</p>
<a-show :message = "inputValue"/>
<p><button @click="handleChangeAppName">修改appName</button></p>
<p>{{ appVersion }}</p>
<p><button @click="handleChangeUserName">修改用户名</button></p>
</div>
</template>
<script>
import AInput from '_c/AInput.vue'
import AShow from '_c/AShow.vue'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
name: 'store',
data () {
return {
inputValue: ''
}
},
components: {
AInput,
AShow
},
computed: {
...mapState({
appName: state => state.appName,
userName: state => state.user.userName,
appVersion: state => state.appVersion
}),
...mapGetters([
'appNameWithVersion',
'firstLetter'
]),
inputValueLastLetter () {
return this.inputValue.substr(-1, 1)
}
},
methods: {
...mapActions([
'updateAppName'
]),
...mapMutations([
'setAppName',
'setAppVersion',
'setUserName'
]),
handleChangeAppName () {
// this.$store.commit('setAppName', {
// appName: 'newAppName'
// })
// this.$store.commit('setAppVersion')
this.setAppName({
appName: 'apache'
})
this.setAppVersion('V 2.0.2')
// console.log(this.$store)
// console.log(this.updateAppName)
this.updateAppName()
},
handleChangeUserName () {
this.setUserName({
userName: 'alibaba'
})
}
}
}
</script>
总结:
1、mapActions是一个方法,注意它的定义位置不能放在computed里,这样会重复调用,产生 is not faction的现象
2、action有异步调用,注意增加时间等待的方法


浙公网安备 33010602011771号