Vue使用Axios异步请求报错集合及解决方案
报错一:TypeError: this.$axios is not a function报错二:TypeError: Cannot set properties of undefined (setting 'msg')
·
报错一:TypeError: this.$axios is not a function
解决方法:
在main.js中引入axios时,修改原型链。添加代码Vue.prototype.$axios = axios;
//引入axios
import axios from 'axios'
import vueaxios from 'vue-axios'
//修改原型链,将axios改写为vue的原型属性
Vue.prototype.$axios = axios;
Vue.use(axios);
Vue.use(vueaxios);
重新启动,成功获取到data.json
报错二:TypeError: Cannot set properties of undefined (setting 'msg')
该错误可以在控制台输出获取到data.json,但无法将数据展示到template中
解决方法:定义局部变量that代替vue对象
完整代码:
<template>
<div>
<h1>用户信息</h1>
<p>{{msg.name}}</p>
<p>{{msg.url}}</p>
<p>{{msg.age}}</p>
<p>{{msg.address.country}}</p>
</div>
</template>
<script>
export default {
name: "userMsg",
data(){
return{
msg: {
name: "",
url: "",
age: "",
address: {
country: "",
province: "",
city: ""
},
}
}
},
beforeRouteEnter:(to,from,next)=>{
console.log("进入路由之前");
//进入路由之前加载json数据,通过vm组件实例访问组件实例中的getData()方法
next(vm=>{
vm.getData();
});
},
beforeRouteLeave:(to,from,next)=>{
console.log("进入路由之后");
next();
},
methods: {
getData: function () {
//this是window对象,不是vue对象
//定义局部变量that代替vue对象
var that = this;
this.$axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (response) {
console.log(response);
that.msg = response.data;
})
/*写法二: this.$axios.get('http://localhost:8080/static/mock/data.json').then(resp=>(that.msg=resp.data));
*/
}
}
}
</script>
<style scoped>
</style>
重新启动,成功将数据展示
更多推荐
已为社区贡献1条内容
所有评论(0)