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

如果你觉得现在有些困难,那证明你是在走上坡路!

文章导航

    • 安装axios
    • 在main.js中引用
    • 【重点】改写为Vue原型属性


安装axios

  npm install axios --save

在main.js中引用

  import axios from 'axios'

【重点】改写为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;
  	});

你可能感兴趣的:(Vue踩坑日记)