【详细】VUE中使用axios (Error in mounted hook: "TypeError: Cannot read property 'XXX' of undefined" 解决)

1、安装axios

  npm install axios --save

2、在main.js中引用

  import axios from 'axios'

3、【重点】改写为Vue原型属性

Vue.prototype.axios = axios

axios不能像其他组件一样通过Vue.use()直接被引用

  Vue.use(axios)
  //axios是无法被其他组件使用的,会出现下面的错误
  Error in mounted hook: "TypeError: Cannot read property 'XXX' of undefined"

要将axios改写为 Vue 的原型属性,才能被其他组件使用

  //绑定到Vue原型上
  Vue.prototype.axios = axios
  
  //当然你也可以自定义变量的名字,在引用的时候使用这个自定义的名字就好了。比如:
  Vue.prototype.$ajax = axios
  //在使用的时候需要这样写
  this.$ajax
  	.get(''/user')
  	.then(res => {
  		this.result = res.data;
  	});
发布了29 篇原创文章 · 获赞 8 · 访问量 4789

猜你喜欢

转载自blog.csdn.net/qq_40738077/article/details/98326806
今日推荐