网络编程 
首页 > 网络编程 > 浏览文章

vue 组件内获取actions的response方式

(编辑:jimmy 日期: 2024/5/17 浏览:3 次 )

最近使用在学习使用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方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:vue中在vuex的actions中请求数据实例
下一篇:在vue中使用vuex,修改state的值示例
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网