[Vuejs]-Rendering lists using v-for in Vuejs?

1👍

You can do somethings like this

<template>
  ...
  <v-app id="inspire" class="ml-4">
    <template>
       <!-- Names -->
      <div v-for="person in myArray1" key="person.name">
        {{person.name}}
      </div>
    </template>
    <template>
      <!-- New names -->
      <div v-for="person in myArray2" key="person.name">
        {{person.name}}
      </div>
    </template>
    <v-btn @click="addNewPerson">
      Add
    </v-btn>
  </v-app>
  ...
</template>
<script>
export default {
  ...
  data() {
    return {
      myArray: [{
          name: 'Sam',
          value: 'sam'
        },
        {
          name: 'Gary',
          value: 'gary'
        },
        {
          name: 'Smith',
          value: 'smith'
        },
        {
          name: 'Sunny',
          value: 'sunny'
        },
        {
          name: 'Michael',
          value: 'michael'
        }
      ]
    }
  },
  computed: {
    myArray1() {
      return this.myArray.filter(it => it.recent !== true)
    },
     myArray2() {
      return this.myArray.filter(it => it.recent === true)
    },
  },
  methods: {
    addNewPerson() {
      this.myArray.push({
        name: 'Michael 1',
        value: 'michael 2',
        recent: true // add this
      })
    }
  }
  ...
}
</script>

0👍

To accomplish what you want, you will either need to use a computed value that returns newly added values by checking if they are in a position that exceeds the original link (or any other method really), so if you first load the component and store that the existing array has 5 elements, you can have a computed that returns the first 5 elements and put that into the first div, then another computed that returns elements 6+ into the second div. Otherwise, you will need to use two separate arrays.

Keep in mind I’m using this.$data here in the example, but the data and the values should be in the store, so it’d be this.$store.state.myArray instead.

<template>
    <div>
        <div v-for="(element, index) of getExisting" :key="index">{{element.name}}</div>
        <div v-for="(element, index) of getNew" :key="index">{{element.name}}</div>
    </div>
</template>

<script>
export default {
    data: () => ({
        created () {
            this.existing = this.myArray.length
        },
        myArray: [
            { name: 'John' },
            { name: 'James' }
        ],
        existing: null
    }),
    computed: {
        getExisting () {
            return this.$data.myArray.slice(0, this.existing)
        },
        getNew () {
            return this.$data.myArray.slice(this.existing, myArray.length)
        }
    }
}
</script>
👤Arc

Leave a comment