Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use axios in vue3

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use axios in vue3". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use axios in vue3.

You need to install axios before you can use it.

Yarn add axios npm install axios bower install axios

The above four installation methods, according to the project you create, choose by yourself.

1. Basic use of axio

First create a component and introduce axios to test whether the introduction is successful or not! Write the following code:

Import axios from "axios" import {onMounted} from "vue" export default {setup () {onMounted (() = > {axios ({url:' https://xxxxxx.net/hj/mp/banner/l'})})}}

OnMounted is a lifecycle hook function, and this network request is called when the page is loaded. The method of axios does not set the network request method. The default is the GET request.

When you open the service and view the network request, you find that the request has failed:

Error content: Access to XMLHttpRequest at 'https://xxxxx/hj/mp/banner/l' from origin' http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Indicates that there is a cross-domain problem.

Second, how to solve the cross-domain problem?

Use the proxy agent to solve this problem, create a new vue.config.js file, and add the configuration:

Module.exports= {devServer: {proxy: {'/ api': {target:' https://xxxxx.net', changeOrigin:true, pathRewrite: {'^ / api':''}

It is awkward to refresh the page to see the effect. The request address is completely correct, but it keeps prompting 404 that the address can not be found.

For the project in vue2, the request is normal, but it is 404 in vue3.

At the network request, add the global configuration and delete the domain name from the url at the request.

Axios.defaults.baseURL ='/ api'axios.defaults.headers.post ['Content-Type'] =' application/json' axios ({url:'/hj/mp/banner/l'})

After the modification is completed, the network request to refresh the page becomes successful.

III. Encapsulation

Do not use a tripartite library, the most talk is how to encapsulate, how to use after encapsulation, does it not smell good to use directly?

To tell you very clearly, it is still too young. Just remember to suffer a few more losses. The biggest advantage of encapsulation is that if there is a bug in the tripartite framework or when you need to change the tripartite, you only need to modify it in one place, which is easy to maintain, less workload, and not easy to miss.

Because there are so many axios request methods, there can be many types of encapsulation.

Method 1:

Import axios from 'axios' / / Global configuration axios.defaults.baseURL = "/ api" axios.defaults.timeout = 5000 / / interceptor axios.interceptors.request.use (config= > {return config}, error= > {return Promise.error (error)}) axios.interceptors.response.use (response= > {return response.data}, error= > {return Promise.error (error)}) export function request (url='',params= {}, type='POST') {/ / set url params type default return new Promise ((resolve) Reject) = > {let promise if (type.toUpperCase () = 'GET') {promise = axios ({url, params})} else if (type.toUpperCase () =' POST') {promise = axios ({method:'POST', url) Data:params})} / / processing returns promise.then (res= > {resolve (res)}) .catch (err= > {reject (err)})} / / call import {request} from'.. / network/request.js'export default {mounted () {request ('/ hj/mp/banner/l') .then (res= > {console.log (res) ) .catch (err= > {console.log (err);})}}

Because the axios return itself is a promise object, we can make it easier to encapsulate the promise object without instantiating the outer layer.

Mode 2:

Import axios from 'axios' / / Global configuration axios.defaults.baseURL = "/ api" axios.defaults.timeout = 5000 export function request (config) {const instace = axios.create ({timeout:50000, method:'post'}) / / request interception instace.interceptors.request.use (config= > {return config}, err= > {}) / / response interception instace.interceptors.response.use (res= > {return res.data}) Err= > {/ / error handling}) return instace (config)} / / call import {request} from'. / request'request ({url:'/hj/mp/banner/l',}). Then (res= > {console.log (res)) ) .catch (err= > {console.log (err);})

There are many ways to encapsulate axios. If you are interested, you can go to the axios document and try to encapsulate one, or collect it. Just copy and use it directly in the future. You don't have to work hard to encapsulate it.

4. Global reference axios

The above encapsulated request method can be referenced globally so that it can be used in any file of the project.

Add global attributes within the main.js

Const app = createApp (App) app.config.globalProperties.$http = requestapp.mount ('# app')

The order of the above three can not be adjusted!

When used within a component:

Import {defineComponent, getCurrentInstance, onMounted} from "vue" export default defineComponent ({setup (props,ctx) {const {proxy} = getCurrentInstance () onMounted (() = > {console.log (proxy); proxy.$http ('/ hj/mp/banner/l') .then (res= > {console.log (res);})}))

Can see the final congratulations, this is the only thing that has changed in the use of axios in vue3.

Thank you for reading, the above is the content of "how to use axios in vue3". After the study of this article, I believe you have a deeper understanding of how to use axios in vue3, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report