您的位置:首页 > Web前端 > Vue.js

VUE 之 axios 使用方法及封装

2019-09-27 16:38 736 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/ws19900201/article/details/101543000
  1. main.js中引入 axios ;
import axios from "axios";
Vue.prototype.axios = axios;

vue文件中使用:

this.axios({
method: "get",
url: '/api/url123',
params: {
area_id: 3,
page: this.pagenum
}
}).then(res => {
console.log(res);
//todosomething
})

2.目前在使用的

新建一个 axios.js 放相同部分的rul;

import axios from "axios";

axios.defaults.baseURL = "http://192.168.0.101/api"; //服务器路径
export default axios;

新建一个 util 文件夹 其中新建一个 fetch.js

import axios from "@/axios"; //引入 刚建的axios文件
import { Message } from "element-ui";
// 创建axios实例
const service = axios.create({
baseURL: axios.defaults.baseURL, // api的base_url
timeout: 120000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
config => {
// config.headers["token"] = window.sessionStorage.getItem("tokens");
// config.headers["Content-Type"] = "application/json";
return config;
},
error => {
// Do something with request error
// console.log(error); // for debug
Promise.reject(error);
}
);

// respone拦截器
service.interceptors.response.use(
response => {
/**
* status为非200是抛错 可结合自己业务进行修改
*/
const res = response.data;
if (res.status != 200) {
Message({
message: res.message,
type: "warning",
duration: 5 * 1000
});
}
return res;
},
error => {
// console.warn("大概是服务器崩溃了,请联系攻城狮"); // for debug
Message({
message: "服务器异常,请稍后重试",
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);

export default service;

新建一个 api 文件夹存放URL 其中新建一个 url.js

import fetch from "@/util/fetch";

export function getBanner(params) {
//添加轮播
return fetch({
url: "/getbanners", //接口路径
method: "get",
params
});
}

export function getnews02(params) {
//添加轮播
return fetch({
url: "/getNewsList",
method: "get",
params
});
}

.vue 文件中使用 ;

import { getnews02 } from "@/api/url.js";
...
created() {
this.getSpecialData();
},
methods: {
getSpecialData() {
const params = {
area_id: 3,
page: this.pagenum
};
getnews02(params).then(res => {
// if (res && res.status === 200) {
// console.log(res);
if (this.pagenum == 1) {
this.datacounts = res.count;
this.newsTop = res.data.topnew;
this.newsList = res.data.list;
this.totalnum = parseInt(this.datacounts / 10);
} else {
this.newsList = [...this.newsList, ...res.data.list];
this.scroll = true;
}
++this.pagenum;
console.log(this.pagenum);
// }
});
}
...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: