What is the reason behind Vue.js duplicating its v-model data when the v-model is used within a computed property?

Consider the code snippet below:

JavaScript

const App = {
  template: '#app-template',
  data: () => ({
    selected: [],
    items: Array.from({length: 50}, (x, i) => i+1).map(i => ({
      id: i ,
      name: `Item ${i}`,
      subtitle: `Subtitle ${i}`
    }))
  }),
  computed: {
    parsedItems() {
      this.selected;
      return this.items.map(item => ({
        someValue: 3,
        ...item
      }));
    }
  }
}

new Vue({
  vuetify: new Vuetify(),
  render: h => h(App)
}).$mount('#app')

HTML

<script type="text/x-template" id="app-template">
  <v-app>
    {{selected}}
    <v-container>
        <v-virtual-scroll
          :items="parsedItems"
          :item-height="65"
          height="500"
        >
          <template v-slot="{ item, index }">
           <v-list-item-group
             v-model="selected"
             multiple
           >
            <v-list-item :key="item.id" :value="item">
              <v-list-item-action>
                <v-checkbox
                  :input-value="selected.includes(item.id)"
                  color="primary"
                />
              </v-list-item-action>
              <v-list-item-content>
                <v-list-item-title>
                  Index: {{ index }} {{ item.name }}
                </v-list-item-title>
                <v-list-item-subtitle>
                  {{ item.subtitle }}
                </v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>
           </v-list-item-group>
          </template>
        </v-virtual-scroll>
    </v-container>
  </v-app>
</script>

<div id="app"></div>

When a checkbox is checked or unchecked, the selected v-model always accumulates an additional instance even if it already contains one.

Removing this.selected; (line 16 in the Codepen link below) resolves the issue.

It seems that this.selected somehow loses its references and fails to recognize previously selected items.

For a practical application, I need to filter and modify items in the list based on previous selections. My current workaround involves converting all objects to string values using JSON.stringify to maintain consistency.

To view the issue in action, visit this Codepen link: https://codepen.io/MichaelKatz/pen/vYXXdgb

Answer №1

The v-model doesn't appear to function with Objects

<v-list-item :key="item.id" :value="item">    <!-- switch this -->
<v-list-item :key="item.id" :value="item.id"> <!-- to this   -->

Additionally, establish a new computed property to "hydrate" those ids:

selectedItems() {
  return this.selected.map(id => this.parsedItems.find(x => x.id === id))
}

Revised Codepen

Answer №2

When trying to access a v-model while filtering the items it refers to, I noticed that it creates a de-reference of the objects within it.

To tackle this issue, I found the most effective solution by including an extra computed property that contains the logic related to this.selected.

Implementing this approach has successfully resolved the problem in my case.

  computed: {
    parsedItems() {
      return this.items.map(item => ({
        someValue: 3,
        ...item
      }));
    },
    filteredItems() { // introducing another computed property that utilizes this.selected
      this.selected;
      return this.parsedItems;
    }
  }
}

Answer №3

Looking at it from my point of view, the issue lies in the utilization of the multiple attribute, which permits multiple selections.

      <template v-slot="{ item, index }">
       <v-list-item-group
         v-model="selected"
         multiple
       >

By simply removing this attribute, you will be able to resolve the problem at hand.

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

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...

What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted differen ...

Error Encountered in NextJS - Hydration Unsuccessful

Currently, I am utilizing NextLink in my project to generate links. However, it appears that using NextLink is causing the following error: Hydration failed because the initial UI does not match what was rendered on the server. Upon inspecting the console ...

Is there a way to identify the source of a div's scrolling behavior?

While working on a complex web page that involves multiple JQuery Dialogs and other widgets, I encountered a frustrating issue. Some of the dialogs contain divs with scrolling abilities (using overflow-y with a fixed height). Whenever I click on one dialog ...

Transferring data between various stages of the user interface

As a newcomer to angularJs, I find myself facing an issue with two forms existing in different UI states (URLs) labeled as Step 1 and Step 2. The process requires filling up Step 1 and moving to the next step by clicking the NEXT button, which then leads t ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Is there a way to programmatically select an HTML tab or filter in puppeteer?

I am currently developing a web scraping application for a website that utilizes tab headers to filter the contents of a table. In order to extract the data from the table, I need to first select a specific filter by clicking on a tab item. However, I&apos ...

Ensuring scope safety in jQuery AJAX requests

My intuition suggests that if I am on a laggy server and the user triggers two events quickly enough, the value of c in the success function will be based on the most recent event, potentially causing func1 to use the incorrect value. This is merely a hypo ...

Please indicate the decimal separator for the Number() function

UPDATE : TITLE IS MISLEADING as testing showed that Number() returned a dot-separated number and the HTML <input type="number"/> displayed it as a comma due to locale settings. I changed to using an <input type="text"/> and filtered keydown lik ...

What is the best way to display a component in Vue.js only when the user is redirected from a specific page?

Like the title suggests, I am looking to have a message appear only if the page is redirected from a specific page. I believe it may be related to either this.$router or this.$route, but I'm having trouble figuring it out. ...

Stop dishonesty in a timed internet assessment

At my company, we frequently host online competitions that involve simple multiple-choice quizzes. The winner is determined by the fastest completion time. Lately, we have been facing a major issue with cheaters submitting quiz entries in less than one se ...

Removing custom scrollbars using jQuery from an element

Utilizing mCustomScrollbar with jQuery UI dialog boxes. When attempting to initialize mCsutomScrollbar on $(window).load as instructed, it fails because the dialogs are not yet visible. As a workaround, I've had to initiate mCsutomScrollbar on the op ...

Ensuring Element-UI table column sizes accommodate content without causing text to wrap to the next line

Is there a way to adjust the column size of an Element-UI table without causing words to break onto the next line? If you take a look at the address column in this example: https://codepen.io/rameezcubet/pen/QWLoMbr I've tried using min-width="100" ...

Troubles encountered when attempting to use Axios to call a third-party API in a React JS application

Challenge Description: I set out to create a dropdown menu of post-offices based on the user-entered pincode. To achieve this, I utilized an API and Axios for the backend request. While I successfully populate the dropdown with the necessary data, the is ...

Utilizing PUG for Iterating Through Multiple Items in Express Framework using JSON Data

I'm currently working on a small application using Express and PUG, aiming to achieve the following: https://i.stack.imgur.com/ZDyTK.png index.pug ul#restaurants-list li img.restaurant-img(alt='Mission Chinese Food', sr ...

Deliver JavaScript and HTML through an HTTP response using Node.js

My attempts to send both a JavaScript file and an HTML file as responses seem to be failing, as the client is not receiving either. What could be causing the client to not receive the HTML and JavaScript files? I am using Nodejs along with JavaScript and H ...

Tips for efficiently exporting and handling data from a customizable table

I recently discovered an editable table feature on https://codepen.io/ashblue/pen/mCtuA While the editable table works perfectly for me, I have encountered a challenge when cloning the table and exporting its data. Below is the code snippet: // JavaScr ...

Performing XMLHttpRequests and ajax requests inside a foreach loop

I am facing a issue with echoing the decoded array using var_dump. Each time I click the button, a unique xmlhttprequest and ajax call should get executed for every row. However, in reality, the ajax doesn't work as expected. Upon examining the source ...

Updating the contents of one specific div without affecting all other divs with the same class

Below is the HTML code snippet in question: <a class="btn test-btn test-btn-1"> <span>Content 1</span> </a> This particular code block appears multiple times on the page. The number at the end of test-btn- is dynamically generat ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...