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.
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:
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:
This example can possibly be simplified but this is how I've used it for a long time.