🎉如果你觉得现在有些困难,那证明你是在走上坡路!
安装axios
npm install axios --save
在main.js中引用
import axios from 'axios'
重点:改写为Vue原型属性
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
//在引用的时候使用 this.axios
//当然你也可以自定义变量的名字,在引用的时候使用这个自定义的名字就好了。比如:
Vue.prototype.$ajax = axios
//在使用的时候需要这样写
this.$ajax
.get('/user')
.then(res => {
this.result = res.data;
});