Home > Enterprise >  What is Best way to rerender the child component when View's Object array changed
What is Best way to rerender the child component when View's Object array changed

Time:10-26

I tried this.$forceupdate() , v-if hack but it didn't work. I am new to Vue.


<template>
  <div >
    <HeroCard v-for="hero in heroes" :key="hero.id" :hero="hero" />
  </div>
</template>
<script>
import HeroCard from "@/components/hero/HeroCard.vue";
export default {
  inject: ["heroStats"],
  name: "HeroList",
  components: {
    HeroCard,
  },
  data() {
    return {
      heroes: this.heroStats,
    };
  },
  methods: {
    filterHeroes(heroStats, primary_attribute, attack_type, roles, name) {
      if (!primary_attribute.length) {
        this.heroes = heroStats;
      } else {
        this.heroes = heroStats.filter((hero) =>
          primary_attribute.includes(hero.primary_attr)
        );
        ...etc
      }
    },
  },
};
</script>

enter image description here

When Checkboxes are checked the HeroCard component should display heroes that including the primary attributes[ 'Strength', 'Intelligence' ]

CodePudding user response:


you can set a flag and when the Object Array changes set that flag to true (visa versa) and then use a v-if to render that component only when that flag is set to true something like

  <div >
    <HeroCard v-if="showComponent" v-for="hero in heroes" :key="hero.id" :hero="hero" />
  </div>
</template>```

CodePudding user response:

I would make heroes to a computed property and filter it with a selected_attributes data property bound to your checkboxes.

data() {
      return {
           heroStats: heroStats,
           selected_attributes: ['Strength', 'Intelligence']
     }
},
computed: {
   heroes() {
       return this.heroStats.filter((hero) =>
        this.selected_attributes.includes(hero.primary_attr)
       );
   }
}

Then the heroes list will be auto-updated, when the checkboxes and selected_attributes changes. This ten will automatically trigger the update of your heroes card list.

 <HeroCard v-for="hero in heroes" :key="hero.id" :hero="hero" />

This is the simplest and most Vue style solution from my point of view.

The Vue reactivity do all the work and you don't need to trigger update of your child components.

  • Related