Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

vue-resource 常用的请求代码段如何独立成service模块?

  • 我们都知道,vue-resouce的请求是要通过Vue实例来调用的

import VueResource from 'vue-resource'
//常量:获取用户数据
const URL_GET_USER_INFO = '/json/getUserInfo';
//请求
var promise = this.$http.get(URL_GET_USER_INFO);
promise.then(function (res) {  
  // 处理成功的结果  
  console.log('this.$http 的請求')  
}).catch(function(res)){
  // 处理失败的结果  
  console.error('this.$http 的請求');
}

  • 需求 :由于获取用户信息的请求很常用,我希望将该代码段封装到一个模块,哪里用到就调用。

service/api.js

//常量:获取用户数据
const URL_GET_USER_INFO = '/json/getUserInfo';
//发送请求
export function getUserInfo(){
  return this.$http.post(URL_GET_USER_INFO);
}

home.vue

//引入模块
import { getUserInfo } from '../service/api.js'
//调用方法
getUserInfo().then(function(){
  console.log('this.$http 的請求') 
}).catch(function(){
  console.error('this.$http 的請求');
});
  • 问题 :提示找不到$htpp对象,难道vue-resource必须要通过Vue实例调用,不能独立成模块吗?

Uncaught TypeError: Cannot read property '$http' of undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

问题解决

service/api.js 传入this执行环境来调用$http即可

//常量:获取用户数据
const URL_GET_USER_INFO = '/json/getUserInfo';
//发送请求
export function getUserInfo(context){
  return context.$http.post(URL_GET_USER_INFO);
}

home.vue

//引入模块
import { getUserInfo } from '../service/api.js'
//调用方法
getUserInfo(this).then(function(){
  //...
}).catch(function(){
  //...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...