vue.js - vue-resource 常用的请求代码段如何独立成service模块?
本文介绍了vue.js - 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
解决方案
问题解决
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(){
//...
});
这篇关于vue.js - vue-resource 常用的请求代码段如何独立成service模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文