Shared data between single-file component instances

1k Views Asked by At

Is there a way to have multiple instances of same single-file component to share data without passing it around with buses or events?
I mean, escept for the data sectione that is the only one declared as a function exactly for this purpose, every other section is in fact shared between istances, right?

What i would like is somethig like static variables for PHP or C classes.

My specific use case

I have a single file component based on a component from a vue library (Carousel from Element UI) that need its height to be defined as a prop, but every instance of my wrapper component has different contents with different heights.
What i thought to do is to make every instance check its contents heights, find the max and set the height of the wrapped carousel.
To do so i can retrieve the dom elements by class and check for the greatest height with js, but i need to be shure that every instance retrieve only its own contents, not the others ones, so i would like to have somethink like a shared counter and have every instance to increment this counter in its created method` and use it to generate its own id.

Is this possible?
If not, is there another way? I would like to avoid passing every instance a prop just for this purpose.

2

There are 2 best solutions below

2
On

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.

0
On

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.