Search code examples
vue.jsvuejs3vue-composition-api

Vue3 Composition API: Multiple instances of same Component share state


I'm working my way through Vue 3 and the Composition API and I can't figure out how to make multiple instances of the same component work.

<Loader />
<Loader />
<Loader />

Loader.vue

export default {
    data() {
        return {
            status: null
        }
    }
}

Now, when the first Loader ist done and sets status, the other <Loader /> components work as expected.

However, when using Composition API like follows, the first <Loader /> that is done sets the status und all the other Components use that new status instead working with there own variables.

const status = ref(null)

How can I achieve this behaviour in Vue3 with Composition API?

I found an old question about a similar problem but this doesn't help with Composition API. I guess, it's related to state management of the components. Also, the official docs don't help.


Solution

  • So I'm not seeing how you are passing the status into the Loader. You should have a property on each of the loaders like this.

    <Loader :status="status"/>
    <Loader :status="status"/>
    <Loader :status="status"/>
    

    And then in Loader you'll have to declare the props

    const props = defineProps(['status']);
    

    Now when you update the status in the parent it should carry through to all the instances.

    If that isn't the issue you are having, another kind of similar issue that often will come up with you have several divs with the same name is the lack of a unique ID. To fix that you'll want to do something like this:

    <Loader :status="status" key="1"/>
    <Loader :status="status" key="2"/>
    <Loader :status="status" key="3"/>
    

    That is normally an issue with foreach loops, but it could be an issue that you are having as well in this case.