vue中axios的使用

文章讲述了在Vue项目中如何安装和使用axios库。首先,通过npm安装axios,然后在main.js中全局引入并挂载到Vue实例上。接着,展示了如何设置请求和响应拦截器以处理请求前后的逻辑。此外,还介绍了如何封装axios实例并导出,以便在其他组件中调用预定义的请求方法,例如获取热门新闻列表。最后,文章提到了在组件中调用这些封装好的请求函数来执行登录操作,并处理响应数据。
摘要由CSDN通过智能技术生成

一、

1.首先npm i axios -s 安装

2.在main.js中导入axios

//引入axios
import axios from "axios"
//挂载在vue上面
Vue.prototype.$axios = axios

3.在created中使用:

this.$axios.get(this.url + '/pc/course/detail/'+this.$router.currentRoute.query.id).then(res=>{
      // console.log(res.data.data)
      this.coverFileUrl = res.data.data.coverFileUrl
    })

二、

  1. 首先npm i axios -s 安装

  1. 在新建文件夹中创建两个js

import axios from 'axios'

// 使用自定义的配置文件发送请求
const instance = axios.create({
    baseURL: '',
    timeout: 5000,
    headers: {
    }
});
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么

    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    instance// 对响应数据做点什么
    if(response.status === 200){
        return response;
    }else{
        console.error("请求错误")
        console.error(response)
    }
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default instance

c.在请求js文件中,如:

import http from './axios'
//获取热门新闻列表
function getHotNews(pageNum=1,pageSize=15){
    let form=new URLSearchParams()
    form.append('pageNum',pageNum)
    form.append('pageSize',pageSize)
    return http.post('/api/api/cms/article/open/hot/list',form)
}

d.在请求中组件中导入封装好的请求函数。如:

import {login} from "@/http/api";

methods{
    login(this.username,this.password).then(res=>{
        if(res.data.code==500){
          //登陆失败通知

          Notify('用户不存在/密码错误');
        }else {
          // 成功通知
          Notify({ type: 'success', message: '登陆成功' });
          this.$router.push('/mine')
          // this.$router.go(-1)
          this.$store.commit('change3',{userinfo:res.data})
        }
      })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WeChat624

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值