Skip to content Skip to sidebar Skip to footer

Vue.js Emit Event From Child Component Not Catched

I have a child component which fetch some data from my server, before fetching I change the loading status to true and I want to set it to false after the fetch is completed. So I

Solution 1:

I solved the problem by using v-show instead of v-if in my template.

<loadingv-show="isLoading":loadingMessage="loadingMessage":isGiphy="true"></loading>

Solution 2:

I know this is an old question, but I stumbled into a similar situation today, and finally understood why the mechanism was working with v-show, and not v-if.

If you get the following <template> tag:

<div><component-av-if="isLoading" /><component-bv-else @set-loading-status="setIsLoading" /></div>

And the following <script> tag:

importComponentA from'./ComponentA'importComponentB from'./ComponentB'exportdefault {
    name: 'ParentComponent',
    components: { ComponentA, ComponentB },
    data() {
        return {
            isLoading: false,
        }
    },
    methods: {
        setIsLoading(isLoading) {
            this.isLoading = isLoading
        },
    },
}

It seems fine, right? You can catch the set-loading-status event from the <component-b> and set it to true. But you can't catch it again to set it back to false.

But, let's take a look in the official Vue docs about v-if and v-show:

v-if is “real” conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.

Now you can see that the component-b gets destroyed when isLoading is set to true, and you won't be able to catch the emitted event to change it back to false.

So, in this particular case, you must use v-show to handle the loading status.

Post a Comment for "Vue.js Emit Event From Child Component Not Catched"