Home > Back-end >  How to have data shared between Vue3 single file component instances?
How to have data shared between Vue3 single file component instances?

Time:09-26

I don't need to pass data between a parent component to a child one or the opposite, I need something like php/c static variables.

I want my sfc (single file component) to have some data that is shared among all instances in in the page.

As far as I understand that's why in sfc we define data as a function

export default {
    data(){
        return {
            // props here
        };
    }
}

while in page scripts we can define it as an object

const app = new Vue({
    data: {
        // props here
    },
}

That's because since we can have multiple instances of a sfc in the page defining its data as a function make each instance to execute in and get its own data, while with page script we can have a singe instance.

I need to define some of my sfc data to be shared between component instances, while other data to be per-instance.

Is there a way to do this?

CodePudding user response:

That depends on the data to be defined, its complexity, and purpose.

If these are 2 or 3 readonly variables, they can be set as global properties using Vue.prototype (Vue 2) or app.config.globalProperties (Vue 3). I'm not sure, because in your example you use Vue 2 syntax.

If the data should be reactive, you can set up a simple state management as explained in the Vue documentation: Simple state management.

If the data is more complex than that, the next step will be Vuex.

CodePudding user response:

Following @Igor answer I looked after the simple state management and found the ref() method that creates reactive primitive values.

In my specific use case I needed to share among all the sfc instances just an array, so in my sfc I had:

const reactive_array = ref([]);

export default {
    data() {
        return {
            shared_array: reactive_array,
        };
    },
};
  • Related