axios是一個庫,並不是vue中的第三方插件,使用時不能通過Vue.use()安裝插件,需要在原型上進行綁定,
例如以下寫法是vue2引入axios的寫法
import Vue from 'vue'
import axios from ‘axios’
Vue.prototype.$http = axios
然而,在vue3.0,並不是直接創建的vue實例,而是通過createApp來創建的
那么問題就來了,這樣的話,
一,vue3.0要通過app.config.globalProperties.$axios = axios進行掛載
二,vue-axios
vue-axios是將axios集成到Vue.js的小包裝器,可以像插件一樣進行安裝
在mian.js中引用axios,vue-axios,通過全局方法 Vue.use() 使用插件,就相當於調用install方法
import axios from 'axios' import VueAxios from 'vue-axios' createApp(App).use(VueAxios, axios)
即可,后續使用,還是照常用
vue.axios.get(api).then((response) => { console.log(response.data) }) this.axios.get(api).then((response) => { console.log (response.data) }) this.$http.get(api).then((response) =>{ console.log( response.data) })
使用 Vue 的插件寫法,更符合 Vue 整體生態環境。直接寫原型鏈,感覺有些粗暴了,搞定