最近用 Vue 写项目的时候,用到 axios ,因为 axios 不能用 Vue.use() ,所以在每个 .vue 文件中使用 axios 时就需要 import , .vue 文件少的话还好说,多的话未免有点麻烦。
后来想了想,能不能直接把 axios 加到 Vue 的原型中,这样就达到了全局注册了。
1. 首先在 main.js 中引入 axios
import Vue from 'vue'import axios from 'axios'//把 `axios` 加到 `Vue` 的原型中Vue.prototype.axios = axios;new Vue({ el: '#app', render:h => h(App)
})2. 在 .vue 文件中使用时,注意 axios 前要加 this
<script>export default { name:'app',
data(){ return{ msg:'hello'
}
}, methods:{
send(){ // 注意:因为 axios 是加到 Vue 的原型中了,所以使用 axios 方法时,前面需要加 this
this.axios.get('https://www.baidu.com*******')
.then(resp => { console.log(resp.data)
}).catch(err => { console.log(err);
})
}
}
}</script>嗯,就这样,结果当然是没有问题的啦!