The biggest difference between vue2 and vue3 is that vue2 uses the options API to compare with the composition API of vue3: aggregate code & amp; Logic reuse
How to use vue3 API to encapsulate Axios in vue2.0:
code directly:
1, create API folder in SRC, and create corresponding file
2, encapsulate some methods in Axios, such as get, post…
// http/axios.js
import instance from "./index"
/**
* @param {String} method Methods requested: get, post, delete, put
* @param {String} url The url of the request:
* @param {Object} data The parameter of the request.
* @param {Object} config The configuration of the request.
* @returns {Promise} returns a promise object, which is actually equivalent to the return value of the axios request data
*/
const axios = ({
method,
url,
data,
config
}) => {
method = method.toLowerCase();
if (method == 'post') {
return instance.post(url, data, {...config})
} else if (method == 'get') {
return instance.get(url, {
params: data,
...config
})
} else if (method == 'delete') {
return instance.delete(url, {
params: data,
...config
}, )
} else if (method == 'put') {
return instance.put(url, data,{...config})
} else {
console.error('未知的method' + method)
return false
}
}
export default axios
3. Encapsulate some Axios request interception and response interception in the index
here, I basically don’t do any interception, I can add them if I need
// http/index.js
import axios from 'axios'
//Create an instance of axios
var instance = axios.create({
baseURL: "http://192.168.0.7:8366", //interface unified domain name
timeout: 6000, //set timeout
headers: {
'Content-Type': 'application/json;charset=UTF-8;',
}
})
let loading;
//Number of requests being made
let requestCount = 0
//Show loading
const showLoading = () => {
if (requestCount === 0 && !loading) {
}
requestCount++;
}
//hidden loading
const hideLoading = () => {
requestCount--
if (requestCount == 0) {
}
}
//Request Interceptors
instance.interceptors.request.use((config) => {
showLoading()
// Determine if a token exists before each request is sent, and if it does, add the token to the header of each http request, so you don't have to add it manually for each request
const token = window.localStorage.getItem('token');
token && (config.headers.Authorization = token)
//If the request method is post, the data parameter is converted to a JSON string
if (config.method === 'POST') {
config.data = JSON.stringify(config.data);
}
return config;
}, (error) =>
// What to do with request errors
Promise.reject(error)).
//response interceptor
instance.interceptors.response.use(( response) => {
hideLoading()
//response success
console.log('Interceptor reported an error').
return response.data;
}, (error) => {
console.log(error)
//Response error
if (error.response && error.response.status) {
const status = error.response.status
switch (status) {
case 400:
message = 'Request Error';
break;
case 401:
message = 'Request Error';
break;
case 404:
message = 'Error requesting address';
break;
case 408:
message = 'Request timed out';
break;
case 500:
message = 'Internal server error!' ;
break;
case 501:
message = 'Service not implemented!' ;
break;
case 502:
message = 'Gateway error!' ;
break;
case 503:
message = 'Service unavailable!' ;
break;
case 504:
message = 'Gateway timeout!' ;
break;
case 505:
message = 'HTTP version is not supported';
break;
default:
message = 'Request failed'
}
ElMessage.error(message);
return Promise.reject(error);
}
return Promise.reject(error);
});
export default instance;
4. Finally, import these files into the NAV file
import axios from "../api/axios"
//Example request
//get
//If you need to wear parameters, you can still use the template string splice `/api/v1/0?id=${id}` and write the id in parentheses
export const mokePostD = (id) => {
return axios({
url: '/api/v1/0',
method: "post",
data,
config: {
headers: {
// 'Request-Type': 'wechat'
},
timeout: 10000
}
})
}
//post
export const mokePost = () => {
return axios({
url: '/api/v1/0',
method: "post",
data,
config: {
headers: {
// 'Request-Type': 'wechat'
},
timeout: 10000
}
})
}
5. Page
import { mokePost, mokePostD } from "../../api/nav";
import { ref, onMounted } from "@vue/composition-api";
export default{
setup(props, { root }){
onMounted(() => {
mokePost().then((res) => {
console.log(res);
});
}
}
}
Read More:
- [Solved] vue3vite Error: Failed to resolve import “@vue/server-renderer from “src\App.vue“. Does the file exist
- How to Solve “Vue is not defined” Error
- Vue displays 404 and 500 interfaces according to HTTP response status
- How to Solve Vue loading 3D model Error
- How to Solve Vue3 Import lodash error
- How to Solve VUE Error: Mixed spaces and tabs
- How to Solve VUE Error: Avoid mutating a prop directly since the value will be overwritten …
- Vue: How to Solve Eslint error
- How to Solve Vue3 jweixin-module Error
- Vue: How to Solve error avoided redundant navigation to current location: “/xxx”
- How to Solve Vue route jump repeated clicks Error
- How to Solve Vue editor bridge error
- [Solved] Vue Error: Uncaught TypeError: Vue.createApp is not a function
- How to Solve Vue cli syntax Close Error
- How to solve Uncaught (in promise) error in VUE?
- Vue: How to Fix “not displaying the holder in IE9 and below”
- Vue3.0 Use el-dialog visible Error: ‘.sync‘ modifier on ‘v-bind‘ directive is deprecated. Use ‘v-model:pro
- [Solved] Vue3 Error: Cannot use ‘in‘ operator to search for ‘path‘ in undefined
- How to Solve Vue cli configuration SCSS global variable error
- How to Solveb Vue3 defineProps Error