Vue使用axios----ReferenceError: axios is not defined问题解决
问题1:ReferenceError: axios is not defined问题代码:const requrl = '/user/find/1'axios.get(requrl).then(response => {const user = response.datathis.username = user.usernamethis.age = user.age}).catch(func
·
问题1:ReferenceError: axios is not defined
问题代码:
const requrl = '/user/find/1'
axios.get(requrl).then(response => {
const user = response.data
this.username = user.username
this.age = user.age
}).catch(
function (error) {
// 请求失败处理
alert('请求失败!')
})
解决方案1:
main.js加上Vue.prototype.$axios = axios
axios.get改为this.$axios.get
调用,修改后不再报错
import axios from 'axios'
//其他vue组件中就可以this.$axios调用使用
Vue.prototype.$axios = axios
const requrl = '/user/find/1'
this.$axios.get(requrl).then(response => {
const user = response.data
this.username = user.username
this.age = user.age
}).catch(
function (error) {
// 请求失败处理
alert('请求失败!')
})
解决方案2:结合vue-axios插件,安装插件后,就不需要将axios绑定到Vue原型链上了,组件内通过this.axios
调用
npm install axios vue-axios --save
import axios from 'axios'
import VueAxios from "vue-axios";
Vue.use(VueAxios,axios)
//其他vue组件中就可以this.$axios调用使用
//Vue.prototype.$axios = axios
const requrl = '/user/find/1'
this.axios.get(requrl).then(response => {
const user = response.data
this.username = user.username
this.age = user.age
}).catch(
function (error) {
// 请求失败处理
alert('请求失败!')
})
问题2,并发测试时,TypeError: Cannot read property ‘$axios’ of undefined
报错代码如下:
function getUserget() {
return this.$axios.get('/user/find/1')
}
function getUserpost() {
return this.$axios.post('/user/find',{id:2})
}
this.$axios.all([getUserget(), getUserpost()])
.then(this.$axios.spread(function (res1, res2) {
// 两个请求现在都执行完成
const user1 = res1.data
const user2 = res2.data
console.log(user1.username)
console.log(user2.username)
}));
原因未知,有知道的大佬还望不吝赐教
无奈只得在app.vue(我是在这里做的测试)中再次引入
import axios from 'axios'
再次引入,直接用axios就行
function getUserget() {
return axios.get('/user/find/1');
}
function getUserpost() {
return axios.post('/user/find',{id:2});
}
更多推荐
已为社区贡献1条内容
所有评论(0)