Martyn Ball
Martyn Ball

Reputation: 4895

Add all vue components to window array

I currently have a strange Vue setup due to our websites all using an old system.

What we have had to do is create an instance of Vue for each component (usually not many). What I want to do for all components is to pass their name and reference to the element into an array, just for reference when debugging issues on live issues.

app.js

import Vue from "vue";
import Axios from 'axios';
import inViewportDirective from 'vue-in-viewport-directive';

window.components = [];

Vue.component( 'video-frame', () => import('./components/VideoFrame.vue' /* webpackChunkName: "video-frame" */) );

Vue.prototype.$event = new Vue();
Vue.prototype.$http = Axios;

Array.prototype.forEach.call(document.querySelectorAll(".app"), (el, index) => new Vue({el}));

Now i'm adding the following code to each component, is there not a way I can do this once within my app.js and have all the components automatically do the following:

mounted() {
    window.components.push({
        tag: this.$vnode.tag,
        elm: this.$vnode.elm
    });
},

Upvotes: 1

Views: 191

Answers (1)

Ayrton
Ayrton

Reputation: 2313

You can use a global mixin like this:

Vue.mixin({
    mounted: function() {
        window.components.push({
            tag: this.$vnode.tag,
            elm: this.$vnode.elm
        });
    }
});

That will ensure that code will run on the mounted hook on every single one of your Vue instances.

Reference: https://v2.vuejs.org/v2/guide/mixins.html

Upvotes: 1

Related Questions