Search code examples
arraysmethodsvuejs2computed-properties

Vue show next amount of items of array


I want to make a button which shows the next 2 items in my array.

The initial amount of the array should be 2 and then when pressing the button it should extend the array with 2 items and so on. When there is only 1 item the button should not be visible.

How can I achieve this? Can I use the slice() method for this?

Here is what I have so far.


Solution

  • You can use slice instead on your computed filteredData with second argument of the slice to be a key that you can modify to tell how many you want the page to show. I will call this productsToShow.

    data: () => ({
        productsToShow: 2,
        products: [...]
    }),
    computed: {
        filteredData() {
          const LowerCaseSearch = this.search.toLowerCase();
          const filteredProducts = this.products.filter(
            product =>
              product.name.toLowerCase().includes(LowerCaseSearch) ||
              product.category.toLowerCase().includes(LowerCaseSearch)
          );
          
          return filteredProducts.slice(0, this.productsToShow);
        }
    }
    

    Then you can modify your ShowNext component-button to emit an event that the parent (List.vue) can listen on to then change the key: productsToShow

    https://codesandbox.io/s/zen-perlman-uhd11