vue 菜菜芥籽学习笔记 ---02

网络请求全局封装

1. 安装请求接口插件

npm i axios

2. utils目录下封装 (request.js)

import axios from "axios"
​
// 创建实例
 const instance = axios.create({
     // 网络请求的基础地址。。设置基础地址后 发送请求时可以省略
     baseURL:"http://localhost:1337"
 });
​
 // 封装get 请求 。axios get请求,参数为路径与配置信息
 export const get =(url,params)=> instance.get(url,{params});
// post 请求
export const post = (url,data)=>instance.post(url,data);

3. 调用接口获取数据 ---use

1. 引入 请求方法

<script>
    import {get} from "../utils/request"
    
     // 创建成功后请求数据
  created(){
    get("/api/v1/products").then((res)=>{
      // 不需要res.data.因为封装请求时,全局响应拦截返回值为res.data
      console.log(res);
      this.datas=res.data
    })
  },
</script>

2. 全局请求拦截,与全局响应拦截

// 全局请求拦截  axios 拦截器,
// Add a request interceptor
instance.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
// 全局响应拦截,返回结果之后执行
// Add a response interceptor
instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    ## 多操作一层,返回res.data
    return response.data;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });
 

4. 同步方式调用接口 (async/await)

<script>
    import {get} from "../utils/request";
    export default{
        async created(){
            const products = await get ("/api/v1/products");
            console.log(products)
        }
    }
    ## 同步方式,不需要(.then)方法

</script>

5. API进化 ,load 封装 (services)

  1. 封装 服务 (方法)

    import {get} from "../utils/request";
    ​
    export function LoadProductsAPI(){
        return get("/api/v1/products")
    }
  2. use,替换get请求,直接调用API方法

    <script>
        import LoadProductsAPI from "../serviices/products";
        export default{
            async created(){
                const products = await LoadProductsAPI();
                console.log(products)
            }
        }
        ## 同步方式,不需要(.then)方法
    </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值