Vue 的 axios二次封装

(以下的接口地址链接换成自己的写!!!)

首先在项目中src的目录下创建一个api的文件夹,在api的文件下在穿件两个文件用于二次封装

别忘了先安装axios:(在根目录下安装axios,如果安装过了,就不用看蓝色字体安装过程)

javascript 复制代码
npm install --save axios

然后在main.js中引用axios:

javascript 复制代码
// 引入axios
import {apiGet,apiPost} from './api/api'
Vue.prototype.$apiGet  = apiGet
Vue.prototype.$apiPost = apiPost

api下的第一个api.js:

javascript 复制代码
import axios from 'axios';
 
axios.defaults.timeout = 30000;
// 这个是环境测试配置,不知道可以搜索我的csdn中的Vue测试打包test
axios.defaults.baseURL = process.env.VUE_APP_API_URL

 
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
 
    //可以写if判断,提前拦截错误信息
 
    return response;
 
}, function (err) {
 
    return Promise.reject(err);
});
 
 
export function apiGet(url, params){ 
	return new Promise((resolve, reject) =>{ 
		axios.get(url, { 
			params: params,
			headers:{"token":sessionStorage.getItem('token')}
		}).then(res => {
			resolve(res.data);
		}).catch(err =>{
			reject(err.data) 
		}) 
   });
}
 
 
export function apiPost(url, params){
	return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url:url,
				data:params
			}).then(res => {
				resolve(res.data);
            }).catch(err =>{reject(err.data)})
        });
    }
 

api下的第二个https.js:

javascript 复制代码
//这个是二次封装(用到apiPost的时候把下面接口那也改成这个,用不到就把apiPost去掉)
import {apiGet,apiPost} from "./api";

export function jindutiao(){
    return new Promise((resolve)=>{
        apiGet("/index.php/index/admin/getNum").then(res=>{
            resolve(res)
})
    });
    // .catch(err=>{
    //     reject(err)
    // })


}

然后按照("jindutiao().这个是https.js中二次封装中你取的函数名字")

先引用:import {jindutiao} from "../api/https"

在使用:jindutiao().then(res=>{

console.log(res);

})

二次封装在页面上的使用以上说的以下示例代码,在script中:

javascript 复制代码
// 这个是二次封装后https.js中封装后直接写函数在这个页面使用
import {jindutiao} from "../api/https"
export default {
    data() {
      return {

      };
    },

    mounted() {

    //    这个是进度条接口
       jindutiao().then(res=>{
            // console.log(res);
            this.percentage = res.data.cssnum;
        this.percentage1 = res.data.htmlnum;
        this.percentage2 = res.data.jsnum;
        this.percentage3 = res.data.vuenum;
        }),

    },
    methods: {


    }
  }
  </script>

如果有跨域问题可以在最后在vue.config.js中添加以下代码解决用注释下面的:

javascript 复制代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  publicPath:'./',
  transpileDependencies: true,
  lintOnSave:false,


  // 跨域问题
  devServer: {
    proxy:{
      '/api1':{
        target:'http://47.94.4.201/',
        pathRewrite:{'^/api1':''},
        ws:true,
        changeOrigin:true,
      }
    }
  }
})
相关推荐
To_OC6 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮7 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny7 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹7 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny7 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC7 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn8 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
REDcker8 小时前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜8 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康9 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端