Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below:

View.component('xxx-item',{
  props:['item'],
  template:`xxxx`,
  computed:{
    computedTest(){
      return this.item.id
    }
  },
  data:function(){
    return{
      test:this.item.id
    }
  }
}

This xxx-item component is used to display items in a list as demonstrated below:

<xxx-list v-for="item in xxxList" v-bind:item="item"></xxx-list>

I expected both this.test and this.computedTest values (representing this.item.id) to be the same. However, they differ at times. Why is that? What distinguishes between the values stored in data and computed?

The item data is populated using the following function:

function loading(){
    axiox.get(xxx)
      .then((res)=>{
        let result = [];
        for(let item of res.xxx.list){
          let obj = {};
          obj.id = item.id;
          .............
          .............
          result.push(obj);
        }
        this.xxxList = result;
      })     
}

Answer №1

Vue optimizes component re-renders by reusing components whenever possible. This means that if you make changes to the xxxList such as adding, removing, or reordering items, some of the <xxx-item> components will be connected to different items. The computed property computedTest will be updated accordingly, but the data property test will remain the same since it was set once during the instantiation of the component.

To ensure that the same component instance is used for the same item in the array, you should use a key on the <xxx-item>.

For example:

<xxx-item v-for="item in xxxList" :key="item.id" :item="item">

When Vue updates a list rendered with v-for, it by default uses an "in-place patch" strategy. Instead of rearranging DOM elements to match the order of the items if they have changed, Vue patches each element in-place to ensure that it reflects the correct data at its specific index.

Answer №2

Whenever the value of the item prop is updated, only the computedTest computed property will reflect this change. The test data property, however, will remain unchanged.

To ensure that the test data property updates every time the item prop changes, you must utilize a watcher.

watch: {
    item: function(item) {
        this.test = item.id
    } 
}

Alternatively, you can achieve this by:

View.component('xxx-item',{
    props:['item'],
    template:`xxxx`,
    computed:{
        computedTest(){
          return this.item.id
        }
    },
    data:function(){
        return{
            test:this.item.id
        }
    },
    watch: {
        item: function(item) {
            this.test = item.id
        } 
    }
}

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

What are the semantics behind implementing Basic Authentication in AngularJS and Spring Boot?

Currently going through a tutorial that involves AngularJS and Spring Security. The AngularJS navigation controller triggers an authenticate function upon page load: var authenticate = function(credentials, callback) { var headers = credentials ? { ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: https://i.sstatic.net/RL3w4.gif I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for th ...

Set up Node to utilize Object.assign

Currently, I am experimenting with Object.assign functionality in IO.js and Node.JS, but encountering an unexpected error. /Users/lp/.nvm/versions/io.js/v2.4.0/bin/iojs --debug-brk=59842 --nolazy mixin.js Debugger listening on port 59842 /Users/lp/Documen ...

What is the best way to show content depending on the selected menu using Vuetify?

Here is the reference I used: https://vuetifyjs.com/en/getting-started/quick-start To set up my project, I executed the following commands: vue create my-app, vue add vuetify, and npm run serve. This is what my App.vue looks like: <template> < ...

Enabling and disabling HTML image input based on checkbox selection

I have utilized the code below to toggle the status of the image button between enabled and disabled modes using JQuery. Here is the code for a checkbox in Yii format: <?php echo CHtml::CheckBox('TermsAgreement','', array ('ch ...

The Socket.io server is experiencing issues with the "connection" event not firing, and the client event is also not being triggered

I've been struggling to set up an express backend with socket io. No matter what I try, the connection events just won't fire. Both the server and client are using version 3.1.2, so that's not the issue. When I start the client app, I see so ...

Typescript PDFjs encountering loading issues with corrupt files

In my Vue.js application, I have the following TypeScript class: /** Taken from https://github.com/VadimDez/ng2-pdf-viewer/blob/master/src/app/pdf-viewer/pdf-viewer.component.ts */ import { Component, Vue } from 'vue-property-decorator'; import ...

What is the method to include a class in the "template" tag within vue?

Can someone please advise on how to attach a class to the "template" tag in Vue? <template #popover class: templateClass // Wishing to include a class here, is it feasible? > <router-link v-close-popover to="/somewhere" ...

Find the most accurate color name corresponding to a hexadecimal color code

When given a hex-value, I aim to find the closest matching color name. For instance, if the hex-color is #f00, the corresponding color name is red. '#ff0000' => 'red' '#000000' => 'black' '#ffff00' = ...

Does the Error page in Next JS 13 fail to properly manage fetch API errors?

After referencing the documentation for Next.js with app router, I followed the instructions to create an error.tsx page within my app folder (app/[lang]/error.tsx). This file contains the code provided in the docs. Additionally, I included some API calls ...

Trigger the animation with a button click by utilizing ng-class in Angular.js

How can I make an animation run more than once when a button is clicked? I've tried using ng-class but it's not working as expected. Any help would be appreciated. Thank you! <div ng-controller="MyCtrl"> <div class='contendor_port ...

The insertion was unsuccessful: Technique used in Meteor 1.3 and React

I am looking to add some simple text to the MongoDB using React. However, when I submit the form, the following error message is displayed in the console: insert failed: Method '/resolutions/insert' not found My setup includes autopublish and i ...

A TypeError is thrown when attempting to use window[functionName] as a function

I came across this page discussing how to call a function from a string. The page suggests using window[functionName](params) for better performance, and provides an example: var strFun = "someFunction"; var strParam = "this is the parameter"; //Creating ...

Securing a JWT token post login

I am new to NodeJS and despite trying numerous solutions, I am facing a challenge. My project involves NodeJS, MongoDB, Express, and Vanilla JS rendered through Pug with an MVC structure. Issue Current Status: I can successfully log in a user and recei ...

Trigger keydown and click events to dynamically update images in Internet Explorer 7

There is a next button and an input field where users can enter the page number to jump to a specific page. Each page is represented by an image, like: <img src="http://someurl.com/1_1.emf" > // first page <img src="http://someurl.com/2_1.emf" ...

Unexpected behavior of TypeScript optional object key functionality

I am facing an issue with an object that has conditional keys. For example: const headers: RequestHeaders = {}; if (...) { headers.foo = 'foo'; } if (...) { headers.bar = 'bar'; } As a newcomer to TS, I initially thought this wo ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

Is it possible to shift the image within the <canvas> element without having to redraw the entire canvas?

I created a game board and I am trying to implement drag-and-drop functionality for my pieces, which are in .gif format. However, I am struggling with finding a solution that allows me to move the pieces without constantly redrawing the entire board. Cur ...

Ways to easily modify images using a single button with the help of jq

I am new to programming and eager to learn... Currently, I am facing the following problem: I would like to create a functionality where three images can be changed using one button and incorporating fadeIn and fadeOut animations. Essentially, all images ...