[Vuejs]-Shared data between single-file component instances

1👍

Answer 1

Use Vuex https://vuex.vuejs.org/ which is the official Vue state management package.

Answer 2

Create a simplified version of it yourself like so:

import Vue from 'vue';

Vue.prototype.$state = {
    shared_variable: false,
    some_counter: 15
};

Vue.mixin({
    data() {
        return {
            $state: Vue.prototype.$state
        }
    }
});

window.Vue = new Vue({
    ...
});

You can then simply refer to this.$state in your components.

If you’d want to watch any of these state variables, you can do so like this:

// Some component.
export default {
    ...
    watch: {
        '$state.shared_variable': function(newVal, oldVal) {
            // Do stuff on change.
        }
    }
}

This example can possibly be simplified but this is how I’ve used it for a long time.

👤Flame

0👍

Answer to my specific use case

Didn’t know about vue $el: this gives me the specific root dom element of my component instance, so no need to generate different ids programmatically with shared data.

However his does not answer the original question about sharing data between component instances.

👤fudo

Leave a comment