axios封装api接口

263 阅读1分钟

建http文件夹 在http下面建http.js文件

import axios from "axios";
export function option(val){
    let server=axios.create({
        baseURL:"http://152.136.185.210:8000/api/h8",
        timeout:6000
    });
    //请求拦截
    server.interceptors.request.use(function (config) {
        return config;
      }, function (error) {
          console.log(error)
      });
      
    // 添加响应拦截器
    server.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        console.log(error)
    });

    return server(val)
}

在http文件夹下面再建一个api.js文件

import {option} from "./http"
//主页数据
export function getHome(){
    return option({
        url:"/home/multidata",
        methods:"get"
    })
} 
//分类列表
export function getList(type,page){
    return option({
        url:"/home/data",
        methods:"get",
        params:{
            type,
            page
        }
    })
}
//详情数据
export function getDetail(iid){
    return option({
        url:`/detail`,
        methods:"get",
        params:{
            iid
        }
    })
}

通过这些方法获取并渲染数据

import {getHome,getList} from "../http/api"

created(){
        getHome().then(response=>{
            console.log(response.data)
            this.banner=response.data.data.banner.list
            this.navList=response.data.data.recommend.list
        });
        getList("new",1).then(response=>{
            console.log(response.data.data)
            this.news=response.data.data.list
        })
        getList("sell",1).then(response=>{
            console.log(response.data.data)
            this.sell=response.data.data.list
        })
}