vue3.0引入axios
首先,我们要知道axios是一个库,并不是vue中的第三方插件,使用时不能通过Vue.use()安装插件,需要在原型上进行绑定import Vue from 'vue'import axios from ‘axios’Vue.prototype.$http = axios然而,在vue3.0,并不是直接创建的vue实例,而是通过createApp来创建的createApp(App)那么问题就来了,
·
首先,我们要知道axios是一个库,并不是vue中的第三方插件,使用时不能通过Vue.use()安装插件,需要在原型上进行绑定
import Vue from 'vue'
import axios from ‘axios’
Vue.prototype.$http = axios
然而,在vue3.0,并不是直接创建的vue实例,而是通过createApp来创建的
createApp(App)
那么问题就来了,这样的话,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 整体生态环境。直接写原型链,感觉有些粗暴了,搞定
更多推荐
已为社区贡献3条内容
所有评论(0)