Manipulating the length of an array based on a specified range using Vue.js

I'm currently working on a client's range filtering feature using Vue.js. The filter involves an input element with the type range to adjust the total number of clients displayed. I have successfully linked the value of the input to the **clients** array. However, there seems to be an issue where the display does not update when increasing the range value.

Here is the template code:

<div id="app">
  <input @input="filteredClients" type="range" min="0" max="10" v-model="clientTotal" />
  <ul>
    <li v-for="(client, index) in clients" :key="index">{{ client }}</li>
  </ul>
</div>

This is the JavaScript code:

const app = new Vue({
  el: "#app",
  data: {
        clientTotal: 10,
        clients: [
            'John Snow',
            'Cullen Bohannon',
            'Jamie Lannister',
            'Jane Doe',
            'Jamie Fraser',
            'John Dow',
            'Claire Fraser',
            'Frank Underwood',
            'Tony Stark',
            'Client Eastwood'
        ],
    },
    mounted() {
        this.filteredClients()
    },
    computed: {
        filteredClients() {
            this.clients.length = this.clientTotal
        }
    }
})

If you'd like to see the full code sample, you can do so by clicking here.

Answer №1

If you're looking to make changes, consider a different approach. Adjusting the length will result in elements being removed from the clients array and then adding empty slots when increasing the length again.

For more information, check out this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

One suggestion is to create a new mapped array called filteredClients. This computed property will update automatically whenever its reactive dependency, clientTotal, changes, without needing to call it on an input event for the range input.

<input type="range" min="0" max="10" v-model="clientTotal" />
<ul>
  <li v-for="(client, index) in filteredClients" :key="index">{{ client }}</li>
</ul>
</div>
const app = new Vue({
  el: "#app",
  data: {
    clientTotal: 10,
    clients: [
      'John Snow',
      'Cullen Bohannon',
      'Jamie Lannister',
      'Jane Doe',
      'Jamie Fraser',
      'John Dow',
      'Claire Fraser',
      'Frank Underwood',
      'Tony Stark',
      'Client Eastwood'
    ],
  },
  computed: {
    filteredClients() {
      return this.clients.slice(0, this.clientTotal);
    }
  }
})

EDIT: In another answer, Neil.Work suggested that using slice instead of map is simpler and more appropriate for this scenario.

Answer №2

The issue arises from the fact that in your code, you are truncating the array by using

this.clients.length = this.clientTotal
. This means that when you try to add more clients later on, the old ones have already been removed.

A better approach would be to modify your filter to

return this.clients.slice(0, this.clientTotoal);
and update your list to use this new computed array instead.

By returning a new array rather than altering the existing one, you can avoid losing any clients in the process.

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

Listening for changes in class property values in TypeScript with Angular involves using the `ngOnChanges`

Back in the days of AngularJS, we could easily listen for variable changes using $watch, $digest... but with the newer versions like Angular 5 and 6, this feature is no longer available. In the current version of Angular, handling variable changes has bec ...

Running a child process in the browser using Node.js with the help of browserify

Utilizing browserify to enable node.js functionality in the browser, I am attempting to run a child process in my index.js file: var exec = require('child_process').exec; //Checking the installed node version var ls = exec('node -v', f ...

Utilize tags as properties in Vue.js by selecting them

I am attempting to retrieve a value from a select tag and use it in an object property. Below is the HTML code: <div id="app"> <h3>{{title}}</h3> <div class="form"> <div class="form-group"> <div ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

Discovering the offset location using touchmove

Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begin ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...

Divide a Multidimensional Array into Separate Arrays

I am working with an array that contains information about users. Each user has attributes like their ID, name, and number of records for today and in total. Array ( [0] => Array ( [u_id] => 2 [u_name] => Test ...

Displaying specific choices depending on the previous selection made

I am facing an issue in Laravel where I have two selection options, and one depends on the other. Despite multiple attempts, I haven't been able to resolve it. The database structure is as follows: companies id title channels id company_id title I ...

Is there a way to execute a Vue method directly from a <div> element?

I'm currently using Blade to control parts of the HTML through conditional rendering. For instance, if the Laravel session login is present, I want to display a div that triggers a Vue method to open a login modal. At the moment, I am utilizing vue-js ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

When utilizing the dispatch function with UseReducer, an unexpected error is triggered: Anticipated 0 arguments were provided,

Having trouble finding a relevant answer, the only one I came across was related to Redux directly. So here's my question that might be obvious to some of you. In my code, everything appears to be correct but I'm facing an error that says: Expect ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Error: Unable to locate module: Could not find '@/styles/globals.scss'

I'm encountering an error message with my import statement for the SCSS file in my _app.tsx. Can someone help me find a solution? I'm working with Next.js and have already exhausted almost every resource available online to fix this issue. ...

How can I set an object as a variable in JavaScript (specifically React) based on two different conditions?

const router = useRouter(); const { locale } = router; const featureId = props.id; let featureContent; featureContent = locale === "en" ? featureContentEn : locale === "de" ? featureContentDe : lo ...

Can you recommend any open source projects with exceptionally well-written Jasmine or Jasmine-Jquery tests?

Currently, I am in the process of learning how to test a new jquery plugin that I plan to develop. I'm curious if there are any notable Github projects like Jasmine or Jasmine-jquery with impressively crafted Jasmine tests that I could explore for in ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Adding an image to a jQuery class name on the fly

I am attempting to add an image before a div by using its className with jQuery. function insertImage(obj) { var dynamicClass = $(obj).prop("className"); After retrieving the classname, I now encapsulate it in single quotes and add a dot to access t ...

Comparing defaultProps with the logical OR operator

Being relatively new to react, I’ve adopted a method of defining default values which looks like this: class TextInput extends Component { render() { return ( <input type="text" name={ this.pr ...

Extract data from an array that has been provided as an argument to a function

int findTwoWins(char currentArray[9]) { char newArray[9]; std::copy(std::begin(currentArray), std::end(currentArray), std::begin(newArray)); Encountering a compilation error here, whereas using a global array works fine. Presumably, the issue is ...

Font size for the PayPal login button

I am looking to adjust the font size of the PayPal Login button in order to make it smaller. However, it appears that the CSS generated by a script at the bottom of the head is overriding my changes. The button itself is created by another script which als ...