>[success] # Vuex -- Action 异步 ~~~ 1.Action 类似于 mutation,不同在于: 1.1.Action 提交的是 mutation,而不是直接变更状态。 1.2.Action 可以包含任意异步操作。 2.上面两句话出自官网,简单的说就是,如果数据是异步获取,在改变state 中的值,我们就不能使用'mutation' 去操作,'mutation' 只能操作一些同步请 求去改变'state' 中的值,因此需要'Action ' 间接控制 3.更多详细的要看文档 ~~~ >[info] ## 使用Action ~~~ 1.详细看看文档 ~~~ >[danger] ##### 在我们的api文件下创建app.js模拟异步 ~~~ export const getAppName = () => { return new Promise((resolve, reject) => { const err = null setTimeout(() => { if (!err) resolve({ code: 200, info: { appName: 'newAppName' } }) else reject(err) }) }) } ~~~ >[danger] ##### 在store.vue 视图中写法 ~~~ 1.在视图使用的时候,想调用'actions' 中的方法需要使用 this.$store.dispatch('actions对应的方法名','传递的参数') ~~~ ~~~ <template> <div> <p>{{appNameWithVersion}}</p> <button @click="handleChangeAppVersion">点击</button> </div> </template> <script> import { mapGetters,mapState, mapMutations} from 'vuex' import state from "../store/state"; export default { name: "store", data(){ return{} }, methods:{ handleChangeAppVersion(){ // actions 中对应方法操控 this.$store.dispatch('updateAppName') }, }, computed:{ ...mapGetters(['appNameWithVersion']), } } </script> <style scoped> </style> ~~~ >[danger] ##### 在action.js 写法 ~~~ 1.actions 中自定义方法,这里使用了es6的用法,把{commit }作为参数使用, 因为'actions ' 给去调用'mutations' 调用'mutations' 只能同过commit,因此可以理 解为什么在'actions' 中的方法参数是'commit' 2.commit('SET_APP_NAME', appName) 第一个参数是调用'mutations'里面的方 法,第二个是传递的参数 ~~~ ~~~ import { getAppName } from '@/api/app' const actions = { updateAppName ({ commit }) { getAppName().then(res => { const appName = res.info; // 内部操作'mutation' commit('SET_APP_NAME', appName) }).catch(err => { console.log(err) }) } } export default actions ~~~ >[danger] ##### 使用mapActions ~~~ 1.在methods 中调用: ...mapActions([ 'updateAppName' ]), 2.在对应使用的地方调用即可 ~~~ ~~~ <template> <div> <p>{{appNameWithVersion}}</p> <button @click="handleChangeAppVersion">点击</button> </div> </template> <script> import { mapGetters,mapState, mapMutations,mapActions} from 'vuex' import state from "../store/state"; export default { name: "store", data(){ return{} }, methods:{ ...mapActions([ 'updateAppName' ]), handleChangeAppVersion(){ // actions 中对应方法操控 //this.$store.dispatch('updateAppName') this.updateAppName(); }, }, computed:{ ...mapGetters(['appNameWithVersion']), } } </script> <style scoped> </style> ~~~