由于一般使用axios,但是每个组件使用的话,每次都要调用axios还要写地址,如果想更改服务器的地址的话,就要一个组件一个组件的更改

所以这就是封装的好处

首先引入axios的依赖

创建request.js

import axios from 'axios'

// create an axios instance
const service = axios.create({
  // baseURL: 'http://chenyp.top:8008', // url = base url + request url
  baseURL: 'http://127.0.0.1:8686', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => config
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    return response.data;
  }
)

export default service

然后在api文件下创建js对接口进行二次封装

import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/service1/login',
    method: 'post',
    data
  })
}

在组件vue文件上对于自己写的方法进行调用

import chapter from "@/api/course/chapter";
 chapter.weekFlush(cid).then(res=>{
	console.log(res.data)
})
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐