vue封装请求与使用

正常的请求

axios
    .get("/api/article/allArticle")
    .then(res => {
    
    
        console.log(res)
    })
    .catch(err => {
    
    
        console.log(err);
    });

封装后使用的请求,需引入api文件()

       this.$api
       //名字为在api中定义的名字,括号内为所需要传的参数
        .allArticle()
        .then((res) => {
    
    
            console.log(res)
        })
        .catch((ree)=>{
    
    
            console.log(ree)
        });
封装步骤

在跟目录文件下创建http文件夹,后在http文件夹下创建api.js文件和index.js文件

index.js文件内容如下
import axios from 'axios'  //引入axios
  //创建一个定义常量service
const service = axios.create({
    
    
    baseURL: '/api',   //地址为配置文件中自己定义的(/api)
    timeout: 10000    //响应时间
})

service.interceptors.response.use(
      (res) => {
    
    
        return res.data
    }, err => {
    
    
        console.log(err)
    })

export default service //抛出
api.js文件内容如下
import service from './index' //先吧index.js文件引入(相对路径)
export default	{
    
    
   //例:此为自定义的名字,在后续使用引入api文件后直接用名字就可以
  allArticle() {
    
    
        return service.get('/recommend')  //get请求后跟接口,如需要传参数要用模板字符串方式
    },
}
main.js中需要挂载
import api from './http/api'


Vue.prototype.$api=api
vue配置文件链接(放在根目录下): link.

提取码: ct2h

猜你喜欢

转载自blog.csdn.net/weixin_49866029/article/details/108238508