Vue3引入axios封装接口的两种方法实例
目录
- 第一种
- 1.安装
- 2.新建一个http.js文件
- 3.使用
- 第二种
- 1.安装
- 2.新建
- 3.http.js
- 4.request.js
- 总结
第一种
1.安装
npm install axios -S
2.新建一个http.js文件
import axios from "axios"; import qs from "qs"; import { Dialog, Toast } from "vant"; // axios.defaults.baseURL = 'http://hplqy.suoluomei.cn/index.php?s=/hfs/Api/' //正式 axios.defaults.baseURL = 'http://activitytest.hpl001.cn/crm_api/app/sinceOrder/' //测试 //post请求头 axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"; //设置超时 axios.defaults.timeout = 10000; axios.interceptors.request.use( config => { Toast.loading({ duration: 0, message: '加载中...', forbidClick: true, }); return config; }, error => { return Promise.reject(error); } ); axios.interceptors.response.use( response => { Toast.clear(); return response; }, error => { Toast.clear(); Dialog.alert({ title: "提示", message: "网络请求失败,反馈给客服" }); } ); export default function axiosApi(type, params, method) { let sign = process.env.VUE_APP_SIGN if (process.env.NODE_ENV === 'production') { sign = localStorage.getItem("wx_sign") } else { sign = 'crm:user:sign:f0c8cbe468f6a34463d198268290903f' } var value = { sign: sign } var data = method == "post" ? qs.stringify(Object.assign(value, params)) : Object.assign(value, params) return new Promise((resolve, reject) => { axios({ method: method, url: type, data: data }) .then(res => { if (res.data.errcode == 0) { resolve(res.data) } else { // 接口错误提示 Toast.fail(res.data.msg); } }) .catch(err => { reject(err) }); }) };
3.使用
import axiosApi from "../utils/http";
tabsHttp() { axiosApi("getProductClassFromCrm", {}, "post").then((res) => { for (let i = 0; i < res.data.length; i++) { res.data[i].type = 0; } this.sebarList = res.data; }); },
第二种
1.安装
npm install axios -S
2.新建
3.http.js
import axios from "axios"; import qs from "qs"; import { Dialog } from "vant"; // axios.defaults.baseURL = 'http://hp.suoluomei.cn/index.php' //正式 axios.defaults.baseURL = 'http://hp.suoluomei.cn/index.php' //测试 //post请求头 axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"; //设置超时 axios.defaults.timeout = 10000; axios.interceptors.request.use( config => { return config; }, error => { return Promise.reject(error); } ); axios.interceptors.response.use( response => { if (response.status == 200) { return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { Dialog.alert({ title: "提示", message: "网络请求失败,请刷新重试" }); } ); export default { post(url, data) { return new Promise((resolve, reject) => { axios({ method: 'post', url, data: qs.stringify(data), }) .then(res => { resolve(res.data) }) .catch(err => { reject(err) }); }) }, get(url, data) { return new Promise((resolve, reject) => { axios({ method: 'get', url, params: data, }) .then(res => { resolve(res.data) }) .catch(err => { reject(err) }) }) } };
4.request.js
import http from './http' const api_key = '233d4cad34c34d343785s34dw3er3ds3234esd4' let sign = process.env.VUE_APP_SIGN if (process.env.NODE_ENV === 'production') { sign = localStorage.getItem("sign") } else { sign = '17a1920fdc3c3c25d1bf7c6dd724f5cf' } const post = (url, data = {}) => http.post( url, Object.assign({ api_key: api_key, sign, }, // { // data: Object.assign({ // role_id: role_id //如果需要再包层data就这样写 // }, // data // ) // } data ) ) const get = (url, params = {}) => http.get( url, Object.assign({ api_key: api_key, sign }, params ) ) // 接口说明 const getFissionCourseList = data => post('getFissionCourseList', data) const getGetrequs = params => get('getFissionCourseList', params) //接口导出 export { getFissionCourseList, getGetrequs }
5.页面引入使用
<template> <div class="box"> <div class="yanjin"> <div class="demo" ref='seder' >欢迎来到VUE3</div> <div class="demo" @click="testClick" >欢迎来到VUE3</div> </div> <div @click="go">跳转页面</div> <div @click="getRquset"> 点我调接口 </div> <meHome :text='132'></meHome> </div> </template> <script> import { getFissionCourseList, getGetrequs } from "../../utils/request"; import { reactive, toRefs, onMounted, onActivated } from "vue"; import meHome from "../me/me.vue"; import { async } from "q"; export default { components: { meHome, }, setup() { // data const state = reactive({ testMsg: "原始值", }); //onLand生命周期 onMounted(async () => { // 进入页面调用接口 init(); console.log(state.testMsg); }); // onshow生命周期 onActivated(async () => {}); // methods事件 const methods = { go() { this.$router.push({ path: "/main", query: { course_id: 123, }, }); }, testClick() { this.$nextTick(() => { this.$refs.seder.innerHTML = "更改了内容"; }); }, async getRquset() { await getGetrequs({ t35: "get" }).then((res) => { console.log(res); }); }, }; const init = async () => { await getFissionCourseList({ t35: "post" }).then((res) => { // console.log(res); }); await getGetrequs({ t35: "get" }).then((res) => { // console.log(res); }); }; return { ...toRefs(state), ...methods, }; }, }; </script> <style src='./index.less' lang='less' scoped> </style>
总结
到此这篇关于Vue3引入axios封装接口的两种方法的文章就介绍到这了,更多相关Vue3引入axios封装接口内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)