Пакет / плагин vue-axios
не мой любимый.Если вы Google vue axios
это первый результат.И я думаю, что это главная причина его популярности.Но это альтернатива.Мы просто переопределяем Vue.prototype.$http
и Vue.prototype.axios
, используя исходную библиотеку Axios
Вам не нужно использовать vue-axios
:
Vue.prototype.$http = axios;
Vue.prototype.axios = axios;
Как мыможно увидеть, что для написания всей функциональности нам требуется столько же строк, сколько и для настройки плагина.
const api = 'https://dog.ceo/api/breeds/list/all';
let childComp;
Vue.prototype.$http = axios;
Vue.prototype.axios = axios;
childComp = {
template: '<div><p>{{msg}}</p></div>',
created() {
console.log('child created');
this.$options._componentTag = 'tag-1';
this.$parent.$options._componentTag = 'parent-tag-1';
},
mounted() {
console.log('child mounted');
},
data() {
return {
msg: 'Hello Vue',
}
},
}
Vue.mixin({
created() {
console.log('parent created');
}
})
const app = new Vue({
el: '#app',
render: h => h(childComp),
methods: {
load: function() {
app.$http.interceptors.request.use(function(request) {
//console.log(app.$options.components);
// I want to access the vuecomponent instance here, how can i do that??
let name = app.$options._componentTag;
console.log(name);
let parentName = app.$root.$options._componentTag;
console.log('C');
console.log(
(name ? (name + ' of ' + (parentName ? parentName : 'root')) :
'root component') + ' for url: ' + request.url + ' body: ' + JSON.stringify(request.body));
return request;
},
function(error) {
return Promise.reject(error)
});
// normally, following code will be run within vue component created hook
// method, this represent the vuecomponent, $http is axios
app.$http.get(api).then((response) => {
//console.log(response.data);
});
},
},
});
app.load();
var Ctor = Vue.extend({
name: 'cool-stuff'
});
var vm = new Ctor();
// console.log(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
<div id="app"></div>