Vue3 學習筆記— Axios 的使用有變化嗎?
本篇文章主要目的就是想告訴我身邊,正在學 vue3 或者 準備學 vue3 的同學,vue3中網絡請求axios該如何使用,防止接觸了一點點 vue3 的同學會有個疑問?生命周期、router 、vux使用都改變了,那 axios 使用有沒有啥改變?
小姐姐
使用 axios 之前,需要先安裝好。
- yarn add axios
- npm install axios
- bower install axios
- <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
上邊的四種安裝方式,根據你創建的項目,自行選擇方式。
一、axio 得基本使用
先創建一個組件,引入 axios 測試一下引入成功沒有!寫入以下代碼:
- import axios from "axios"
- import { onMounted } from "vue"
- export default {
- setup(){
- onMounted(()=>{
- axios({
- url:'https://xxxxxx.net/hj/mp/banner/l'
- })
- })
- }
- }
onMounted 是生命周期鉤子函數,頁面加載完成,就會調用這個網絡請求。axios的方法沒有設置網絡請求方式。默認是 GET 請求。
打開服務,查看網絡請求的時候發現,請求失敗了:
報錯內容: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.
提示存在跨域問題。
二、如何解決跨域問題?
使用 proxy 代理解決這個問題,新建 vue.config.js 文件,添加配置:
- module.exports={
- devServer:{
- proxy:{
- '/api':{
- target:'https://xxxxx.net',
- changeOrigin:true,
- pathRewrite:{
- '^/api':''
- }
- }
- }
- }
- }
刷新頁面查看效果的時候就尷尬了,請求地址完全正確,但是一直提示 404 找不到地址。
vue2中的項目,請求正常,但是在vue3中就是404。

在網絡請求處,添加全局配置,并把請求處的url中域名刪除掉。
- axios.defaults.baseURL ='/api'
- axios.defaults.headers.post['Content-Type'] = 'application/json'
- axios({
- url:'/hj/mp/banner/l'
- })
修改完成后,刷新頁面網絡請求就變成成功了。
三、封裝
沒用一次三方庫,講最多的就是如何封裝,封裝后如何使用,直接用不香嗎?
很明白地告訴你,還是太年輕....多吃幾次虧就記住了。封裝最大優點就是,如果三方框架內有 bug 或者需要更改三方的時候,你只需要修改一個地方就修改完了,維護方便,工作量小,還不容易遺漏。
由于axios請求方法很多,所以封裝的時候可以有多種類型。
方式1:
- import axios from 'axios'
- //全局配置
- axios.defaults.baseURL = "/api"
- axios.defaults.timeout = 5000
- //攔截器
- 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'){
- //設置 url params type 的默認值
- 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
- })
- }
- //處理返回
- promise.then(res=>{
- resolve(res)
- }).catch(err=>{
- reject(err)
- })
- })
- }
- //使用時調用
- import {request} from '../network/request.js'
- export default {
- mounted(){
- request('/hj/mp/banner/l').then(res=>{
- console.log(res);
- }).catch(err=>{
- console.log(err);
- })
- }
- }
由于 axios 返回本身就是一個promise對象,所以我們可以不給外層實例化 promise 對象,封裝變得更簡單。
方式2:
- import axios from 'axios'
- //全局配置
- axios.defaults.baseURL = "/api"
- axios.defaults.timeout = 5000
- export function request(config){
- const instace = axios.create({
- timeout:50000,
- method:'post'
- })
- //請求攔截
- instace.interceptors.request.use(config=>{
- return config
- },err=>{})
- //響應攔截
- instace.interceptors.response.use(res=>{
- return res.data
- },err=>{
- //錯誤處理
- })
- return instace(config)
- }
- //使用時調用
- import {request} from './request'
- request({
- url:'/hj/mp/banner/l',
- }).then(res=>{
- console.log(res);
- }).catch(err=>{
- console.log(err);
- })
axios的封裝方式有很多,感興趣的同學,可以自己去 axios 文檔了解下,試著自己封裝一個,或者收藏一下,日后直接復制使用就好了,不用再辛苦封裝了。
四、全局引用 axios
可以把上述封裝的 request 方法,通過全局引用,這樣在項目的任意文件內就都可以使用了。
在main.js內添加全局屬性
- const app = createApp(App)
- app.config.globalProperties.$http = request
- app.mount('#app')
上述三者的順序不可以調整哦!
在組件內使用時:
- 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);
- })
- })
- }
- })
能看到最后的恭喜你了,vue3中axios使用有變化的也就這點東西了。