0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The simple state management seems the best option, but i can't figure out how to implement it in a single file component, every example i found use plain js and not sfc; can you point me in the right direction?
0

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,
        };
    },
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.