Home > Net >  Is there a way to "un-slice" an array on click?
Is there a way to "un-slice" an array on click?

Time:01-19

Let's say I have a list of 10 items inside a div. When the page is loaded I only want the first 3 items to show up in the div, but when clicking on it, I want all 10 to show. If I click a second time they will go back to just showing 3.

I know that I can remove the items by using slice, but how do you get the items back after slicing them?

<template>
 <div>
   <div v-for="item in items">
      {{ item }}
   </div>
  <button @click="showItems">Hide/Show list</button>
  </div>
</template>
<script>
   data(){
      return {
         items: [ ...some list]
    }
   },
  methods: {
     showItems() {
        this.items.slice(0,2) /* I want this to either slice or show all on slick */
    }
  }
</script>

CodePudding user response:

You can create boolean variable which changes it's state on click. Then you can create method or computed property, which returns array (if your variable equals true return array itself, otherwise return sliced array)

Here is the example (didn't check, but should work)

<template>
 <div>
   <div v-for="item in getItemsList()">
      {{ item }}
   </div>
  <button @click="showItems">Hide/Show list</button>
  </div>
</template>
<script>
   data(){
      return {
         items: [ ...some list],
         showAll: true,
    }
   },
  methods: {
      showItems() {
        this.showAll = !this.showAll;
      },
      getItemsList() {
        if (!this.showAll) {
          return this.items.slice(0, 2);
        }
        return this.items;
      }
  }
</script>

CodePudding user response:

The more easy way would be to show/hide instead of using the slicing/unslicing process.

Just use a condition to show all or only 3 by using a data property. Here is a way-

Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data() {
    return {
      showAll: false,
      items: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
  },
  methods: {
    showItems() {
      this.showAll = !this.showAll;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <template v-for="(item, index) in items">
      <div v-if="!showAll && index < 3 || showAll">
        {{ item }}
      </div>
    </template>
    <button @click="showItems">Hide/Show list</button>
  </div>
</div>

  • Related