vue 组件内获取actions的response方式

最近使用在学习使用vuex,想利用vuex集中管理状态。在和后台进行数据交互的时候,必然会涉及接口的调用,此类异步操作,通常写在action里面:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use('Vuex');

const actions = {
 getComplete ({}) {
  return new Promise((resolve, reject) => {        
    Vue.http.get('XXXXXX').then((response) => {
      resolve(response);
     }).catch((response) => {
      reject(response);
     });
    });
  }
 }

export default new Vuex.Store({
 actions
})

这里将接口的请求放置在promise中,利用promise异步的特性,可以在子组件中获取到接口调用成功后返回的参数:

export default {
  ......
  created: function() {
    this.$store.dispatch('getComplete').then(response => {
      ......
    }).catch(response => {
      ......
    })
  }
}

除了这种方式,也可以使用mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store),具体使用方式详见:

传送门:https://vuex.vuejs.org/en/actions.html

以上这篇vue 组件内获取actions的response方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。