Home > front end >  Vue: How to get rid of duplicate content
Vue: How to get rid of duplicate content

Time:01-27

I have an array of names using v-for I get the names, as you can see I have two v-fors where the content is duplicated in this example my content is small and doesn't look so scary in real life it can be much bigger and all the problem is that the content is repeated, I tried to apply slots but could not cope

Template

<template>
  <div>
    <div v-for="(item, index) in array" :key="index" >
      <div >
        <p>{{ item.name }}</p>
      </div>
      <div
        v-for="(girlNames, index) in item.girlNames"
        :key="index"
        
      >
        <div >
          <p>{{ girlNames.name }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

Script

<script>
export default {
  data() {
    return {
      array: [
        { name: "Alex" },
        { name: "Jacob" },
        { name: "Robert" },
        {
          girlNames: [
            {
              name: "Anna",
            },
            {
              name: "Kiwi",
            },
            {
              name: "Ava",
            },
          ],
        },
      ],
    };
  },
};
</script>

Yes, this picture shows where the content is repeated

enter image description here

You can also see code example in codesandbox

CodePudding user response:

The only problem I see here is bad data structure. In my opinion it should be an object with two fields, which seperate in your case boys and girls, and in this object should be actual data:

<script>
export default {
  data() {
    return {
      names: {
          boys: [
              { name: "Alex" },
              { name: "Jacob" },
              { name: "Robert" },
            ],
          girls: [
              { name: "Anna" },
              { name: "Kiwi" },
              { name: "Ava" },
            ]
          }
        },
      ],
    };
  },
};
</script>

They your code in template will be like:

<template>
  <div>
    <div >
      <div v-for="(item, index) in name.boys" :key="index" >
        <p>{{ item.name }}</p>
      </div>
      <div v-for="(item, index) in name.girls" :key="index" >
        <p>{{ item.name }}</p>
      </div>
    </div>
  </div>
</template>
  •  Tags:  
  • Related