Can the parameters in a .slice() be customized within a v-for loop?

I am currently working with Laravel 8 and using blade syntax. The following code snippet is from a Vue component I created:

<li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" 
v-if="comic.item_type === 'b' && comic.stock > 0" 
v-for="(comic, index) in [...list].slice(0, 20)">

within the

.slice(0, 20)

I want to make the number 20 dynamic. My goal is to limit the rendered items to 20 initially, and then allow users to load more by clicking on a button that increments this parameter by 20 each time.

As a beginner in Vue, I'm open to suggestions for better approaches if they exist!

I attempted to bind a variable as the second parameter, but it resulted in an error since it's not intended to be used in that manner.

Answer №1

Here is an example snippet you can try:

const app = Vue.createApp({
  data() {
    return {
      list: [{"id": 1, "name": "aaa", "item_type": "b", "stock": 9, }, {"id": 2, "name": "bbb", "item_type": "b", "stock": 11, }, {"id": 3, "name": "ccc", "item_type": "b", "stock": 8, }, {"id": 4, "name": "ddd", "item_type": "b", "stock": 8, }, {"id": 5, "name": "eee", "item_type": "b", "stock": 8, }, {"id": 6, "name": "fff", "item_type": "a", "stock": 8, }, {"id": 7, "name": "ggg", "item_type": "b", "stock": 8, }],
      nr: 2
    }
  },
  computed: {
    filteredItems() {
      return [...this.list.filter(l => l.item_type === 'b' && l.stock > 0)]
    },
    items() {
      return this.filteredItems.slice(0, this.nr)
    }
  },
  methods: {
    loadMore() {
      this.nr = this.nr + this.nr
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <ul>
    <li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" v-for="(item, index) in items">
      {{ item.name }}
    </li>
  </ul>
  <button @click="loadMore" v-if="nr < filteredItems.length">more</button>
</div>

Answer №2

One possible solution is to utilize a computed list variable that contains the pre-filtered list alongside an index called loadMoreTimes (indicating how many times the "load more" button has been clicked) to easily access the filtered list as follows:

computed: {
  filteredList() {
    return this.list
             .filter(comic => comic.item_type === 'b' && comic.stock > 0)
             .slice(0, (this.loadMoreTimes + 1) * 20);
  }
}

You can then iterate over this array in your template:

<li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" 
v-for="(comic, index) in filteredList">

By the way, it's generally not recommended to use both v-if and v-for on the same element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to trigger a function from a specific div element and showcase the JSON data it retrieves in

I am working with a React JS code page that looks like this: import React, { useState } from "react"; import { Auth, API } from "aws-amplify"; function dailyFiles(props) { const [apiError502, setApiError502] = useState(false); // Extracted into a re ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Click once to expand all rows in the table with ease

I have successfully created a basic table using HTML. The table includes nested elements that are designed to open individually when clicked on the assigned toggle. Essentially, clicking on a '+' icon should reveal a sub-menu, and clicking on a & ...

Sending data using jQuery's AJAX feature

Here is an example of the code I have: var loadUrl = 'test.php'; var dataObject = { category_id: category_id, grade_val: grade }; jQuery.ajax({ type: 'POST', url: loadUrl, data: dataObject, dataType: 'html', ...

Angular Date Filtering to Show dd-mm-yyyy Format

I am having trouble filtering the date correctly in my controller. My desired date format is Thu Mar 31 2016 05:05:00 GMT-0400 (EDT). However, when I use the code mentioned above, the results show up as 03-31-2016. This is the code snippet from my contr ...

The $mdSticky feature in AngularJS Material seems to be malfunctioning

It's been a challenge for me to get the md-toolbar to stay in the top position. I decided to create a custom directive using the $mdSticky service in AngularJS. var app=angular.module('app',['ngMaterial']); app.controller(&apos ...

Error: Unable to access the 'push' property of an undefined element while utilizing Vue router along with Vue 3

Hello everyone, I've encountered an issue with Vue 3 and Vite. I'm attempting to utilize the router but am facing difficulties as it cannot be found. props: ["usuario", "senha"], setup(props) { const errorMessage = ...

Discover Your Location in the Web Browser

My webpage includes the following JavaScript code to obtain the user's location: state.currentTimer = navigator.geolocation.watchPosition(success, error, { enableHighAccuracy: true, maximumAge: 5000 }); The page is designed to be accesse ...

Certain iFrame instances are unable to display specific cross-domain pages

I'm currently working on a project to create a website that can embed external cross-domain sites, essentially like building a browser within a browser. I've been experimenting with using iFrames for this purpose: While it works for some pages, ...

Accessing location information using jQuery from Google's Geocoding API

Recently, I've been delving into the realm of Google Maps Geocoding and attempting to comprehend how to decipher the JSON data that it transmits back. This snippet showcases what Google's response looks like: { "results" : [ { ...

What is the best way to display the current time (generated through JavaScript) within a designated div element?

During my JavaScript studies, I stumbled upon the following code snippet: function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); document.body.innerHTML = hours+":"+mins+":"+sec ...

The issue with Jquery .post function not functioning properly within a popup div

After spending countless hours on this issue, I feel like I'm at a loss... The problem lies in a div that pops up with a button, where the button fills data into different sections of the HTML... Everything works fine except for when I use ajax to c ...

The v-validate feature in Vue.js seems to be encountering issues when used in conjunction with

Why is 'v-validate' not functioning correctly in vue.js with <multiselect> when I submit the form using v-on:submit.prevent='fun()'? <div class="select-inp"> <multiselect v-model="selectedShifts" tra ...

Obtaining a group object when the property value matches the itemSearch criteria

What is the best way to extract specific objects from a group when one of their properties has an array value, specifically using _.lodash/underscore? { "tileRecords" : [ { "tileName" : "Fama Brown", "tileGroup" : ["Polished", "Matt", ...

"Embed" three.js within SmartMS

Is it possible to incorporate this simple three.js example into Smart Mobile Studio without extensive wrapping? I attempted to copy the window.onload content into an asm section but was unsuccessful. <!DOCTYPE html> <html> <head> <t ...

A curious phenomenon observed in the behavior of the jQuery offset() method

Once I executed the following code snippet multiple times: $view.offset({ left : X, //X remains constant top : this.y }); console.log($view.offset()); //displays expected output I noticed (using Firebug) that the HTML code looked like this: <di ...

Access the CSV file using Office365 Excel via a scripting tool

Objective I want to open a CSV file using Office365's Excel without actually saving the file on the client's machine. Challenge The issue with saving raw data on the client's machine is that it leads to clutter with old Excel files accumu ...

Troubles with a Chrome Extension for JSON

I'm currently working on a project to develop a Google Chrome extension and I've encountered an obstacle. I'm experimenting with JSON data (with the intention of integrating it with an API in the future). I have a sample JSON file, successfu ...

Decoding an array in JSON format from PHP

Hey there! Currently, I am working with an associative array in my PHP file, which I convert into a JSON object and pass to my JavaScript file. My goal is to loop through this array and identify the item with a matching key. Here's what I have done so ...

Display a page in Laravel with a specific value

I am attempting to create a button that will set a variable and then refresh the page with the same variable included along with its value. I have tried implementing the code snippet below, but unfortunately it is not functioning as expected. public functi ...