1. 程式人生 > 其它 >vue axios介面封裝及使用

vue axios介面封裝及使用

技術標籤:vue

request.js檔案

import axios from 'axios'
import { Loading, Message } from "element-ui";

const service = axios.create({
    baseURL: '介面地址',
    timeout: 5000,
})

service.interceptors.request.use(
    config => {
        if (typeof config.data == "object") {
            if
(window.sessionStorage.getItem("user_id")) { config.data.user_id = window.sessionStorage.getItem("user_id") } } return config; }, error => { return Promise.reject(error); } ); service.interceptors.response.use
( response => { const res = response.data; if (res.code !== 200) { Message({ message: res.msg || 'Error', type: 'error', duration: 2 * 1000 }); return Promise.reject(new Error(res.msg || '拒絕')); }
else { return res; } }, error => { Message({ message: error.message, type: "error", duration: 5 * 1000 }); return Promise.reject(error); } ); export default service

api檔案 index.js

import request from '@/utils/request'

// 首頁banner圖
export const getUser = (data) => request({
    url: '/login/get_user',
    method: 'POST',
    data
});
// 主題課程
export const culum = (data) => request({
    url: '/index/culum',
    method: 'POST',
    data
});

元件中使用:

import { banner,culum } from "../api/index";
methods:{
// 獲取banner
 getBanner() {
   banner().then((res) => {
   // console.log(res);
   this.bannerList = res.data.banner;
   });
 },
 getCulum() {
   culum().then((res) => {
   // console.log(res);
   this.culumList = res.data.category;
   });
 }
}