(二)vue开发 - 使用vue-resource实现网络请求

vue-resource网络请求

新建一个network.js ,里面内容编辑如下

/**
 * 网络请求
 */
const protocol = window.location.protocol == 'https:' ? 'https:' : 'http:';
const host = protocol + "//www.xxxx.com";
import Vue from 'Vue';
import VueResource from 'vue-resource';
Vue.use(VueResource);

const NetWorkUtils = {
    /**
     * GET 请求
     * @param url
     * @returns {Promise}
     */
    get: function (url) {
        url = url.indexOf("http") < 0 ? host + url : url;
        return new Promise((resolve, reject) => {
            Vue.http.get(url)
                .then((res) => {
                    resolve(res.body);
                })
                .catch((res) => {
                    reject(res.body);
                });
        });
    },


    /**
     * post 请求
     * @param url
     * @param params
     * @returns {Promise}
     */
    post: function (url, params) {
        url = url.indexOf("http") < 0 ? host + url : url;
        return new Promise((resolve, reject) => {
            let opt = {
                emulateJSON: true,
                data: this.formData
            }
            Vue.http.post(url, params, opt)
                .then((res) => {
                    resolve(res.body);
                })
                .catch((res) => {
                    console.log("post error result==", res.body);
                    reject(res.body);
                });
        });

    }
}
export default NetWorkUtils;

在.vue文件里面使用
先导入network

import Network from '../assets/scripts/networks'

调用方式:

Network.post('/login/user', {
    userName:'',pwd:''
}).then((res) => {
   // 请求成功
}).catch((res)=>{
   //异常
});

Network.get('/get/list').then((res) => {
   // 请求成功
}).catch((res)=>{
   //异常
});

猜你喜欢

转载自blog.csdn.net/u010394015/article/details/79132429