AllenC
AllenC

Reputation: 2754

Mounted only trigger once in dynamic component

In my App.vue

I'm using dynamic component to render dynamic component coming from Vuex

<component :is="$store.getters.getDynamicComponent"></component>

then in my Home.vue

<v-card @click="showDetails">
  <v-card-title primary-title>
     <div class="mb-0 text-truncate"> {{name}} </div>
  </v-card-title>
</v-card>

import Details from '@/components/UI/Details';

export default {
  name: 'Home',
  methods: {
    showDetails() {
      console.log('Mount Dynamic Component');
      this.$store.commit('SET_DYNAMIC_COMPONENT', Details);
    }
  }  
}

then on the Details component

export default {
  name: 'Details',
  mounted: {
    console.log('This component has been mounted');
  }
}

The mounted lifecycle trigger only once when I click the card in Home.vue I'm expecting that everytime I click the card it should print

Mount Dynamic Component

and

This component has been mounted

Upvotes: 0

Views: 2014

Answers (2)

AllenC
AllenC

Reputation: 2754

I manage to solve this by using updated lifecycle instead of mounted.

In Details component

export default {
  updated() {
    if (this.$store.getters.dynamicComponent) {
      console.log('This component has been mounted');
    }
  }
}

@fabruex solution also works but in my case I'd rather don't define another state in my vuex just for the key.

Upvotes: 0

Fab
Fab

Reputation: 4657

You can define in your vuex state a numeric variable (i.e. dynamicComponentKey) that will work as key for the dynamic component, and increment it in your SET_DYNAMIC_COMPONENT mutation.

This should force the remount of component when the key will change.

Then, in your App.vue:

<component :is="$store.getters.getDynamicComponent" :key="$store.getters.getDynamicComponentKey"></component>

Upvotes: 2

Related Questions