Reasons Why Vue Component Does Not Update When Select Changes

I'm encountering an issue with a form that is supposed to change text within a vue component based on the selection made in a select box. To demonstrate the problem I'm facing, I've created a simplified version of the code on jsfiddle:

https://jsfiddle.net/ywaug7ft/

Here's the HTML snippet:

<div id="app">
<h5>Select a gender</h5>
  <select v-model="gender">
    <option disabled="disabled" value>Select...</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
    <option value="3">Couple</option>
  </select>
  <div></div>
  <detail-component v-for="(detail, index) in details" :data="detail" :index="index"></detail-component>

  {{details}}
</div>

<template id="details">
   <div>
     <h4><span v-if="item.gender == 3 && index == 0">Her</span><span
                v-else-if="item.gender == 3 && index == 1">His</span><span v-else>Your</span> Health Details</h4>
     <div>Index: {{index}}</div>
     <div>Gender: {{item.gender}}</div>
   </div>
</template>

And the Vue section:

Vue.component('detail-component', {
  template: '#details',
  props: ['data', 'index'],
  data() {
    return {
      item: {
        gender: this.data.gender
      }
    }
  }
});

var app = new Vue({
  el: '#app',
  data: {
    gender: '',
    details: [],
    options: {
        gender: {
        "1": "Single Female",
        "2": "Single Male",
        "3": "Couple"
      }
    }
  },
  watch: {
    gender: function(val) {
      this.details = [];
      if (val == 1) {
        this.details.push({gender: 1});
      } else if (val == 2) {
        this.details.push({gender: 2});
      } else if (val == 3) {
        this.details.push({gender: 3}, {gender: 3});
      }
    }
  }
});

The issue arises when selecting female or male, the vue component should display Your Details. If couple is selected, it should show Her Details and His Details. However, the first index does not update to Her but remains as Your.

Please check out the jsfiddle link provided to see the exact problem.

I'm trying to figure out what mistake I might be making here. My understanding was that using a watcher would make the component reactive. Any insights into my error would be greatly appreciated.

Answer №1

Always remember to keep an eye on any changes happening inside the child component when updating a prop value.
Make sure to watch for changes in the prop data in the child component whenever it gets updated.

Check out this interactive example on Fiddle.

watch:{
  data(val){
    this.item.gender=val.gender
  }
}

You can also use a computed property by referring to this Fiddle.

computed:{
  item(){
    return this.data;
  }
}

Answer №2

You have encountered an issue with your references in the detail-component. The component is receiving data, but you are referring to item in your template.

To resolve this, update your template like this:

<template id="details">
   <div>
     <h4>
         <span v-if="data.gender === 3 && index === 0">Her</span>
         <span v-else-if="data.gender === 3 && index === 1">His</span>     
         <span v-else>Your</span> 
         Health Details
     </h4>
     <div>Index: {{index}}</div>
     <div>Gender: {{data.gender}}</div>
   </div>
</template>

After making these changes, it should work correctly (you can view the updated version on this Fiddle).

The issue stemmed from having gender as 1 in the initial detail object, resulting in "Your" instead of "Her".

Answer №3

One scenario that caused issues for me was having :v-model in the template when it should have been just v-model. Something as simple as missing a colon can lead to everything breaking.

Answer №4

The issue stems from this segment of your code:

  data() {
      return {
        item: {
          gender: this.data.gender
        }
      }
    }

By assigning the value of the gender property from your prop to a property within your data() object, its reference is lost immediately. Consequently, when the data prop was updated, it did not reflect in your item.gender.

If you only intend to create an alias for the gender with a shorter name for convenience, you can utilize computed properties, which will also update whenever the data changes.

computed: {
    item() {
      return this.data
    }
}

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

Seeking assistance with transmitting data to the server and retrieving it for use. I am looking to achieve this goal utilizing JavaScript with Node.js

I've been experiencing challenges with the interactions between front-end and back-end. I am confident that I am sending the data, but unfortunately, I am unable to access it afterwards. Recently, I utilized this code template (sourced from Mozilla&ap ...

Issues arise when trying to use a JavaScript function within an HTML form, with an error message stating "TypeError: total

Recently, I encountered an issue with a straightforward JavaScript function that calculates user input. The function performed as expected when I tested it without the form tag. However, when I tried using the same code within the form tag, an error was di ...

Leverage the exported data from Highcharts Editor to create a fresh React chart

I am currently working on implementing the following workflow Create a chart using the Highcharts Editor tool Export the JSON object from the Editor that represents the chart Utilize the exported JSON to render a new chart After creating a chart through ...

The ng-click function ceases to trigger after the $location dependency is included in the controller

I need some help with running a ng-click function from my controller. The strange thing is, when I don't use the $location dependency, the ng-click function works fine. But as soon as I add $location to the controller, the ng-click function stops work ...

Use JavaScript to change the CSS pseudo-class from :hover to :active for touch devices

Looking to eliminate hover effects on touch devices? While it's recommended to use a hover class for hover effects, instead of the hover pseudo-class, for easier removal later on, it can be a challenge if your site is already coded. However, there&apo ...

Issue encountered with Vue.js build configuration not being loaded while running on the build test server

I am working on a Vue 2 project and facing an issue with loading configuration settings from a config.json file. My router\index.ts file has the line: Vue.prototype.$config = require('/public/config.json') The config.json file contains imp ...

Error message in node.bcrypt.js: 'No callback function provided; result is undefined.'

Currently, I am enrolled in Mosh Hamdani's Mastering React Course and have encountered some challenges with back-end development. The most recent issue is an error message stating: “undefined No callback function was given” when attempting to regi ...

What is the process of generating a VectorSource in OpenLayer 6.5 using a JavaScript object?

I'm in the process of developing a web application that utilizes OpenLayer 6.5. I need to dynamically mark certain locations without storing ".geojson" files on the server. Any suggestions on how I can achieve this? When attempting to create a Vector ...

Occasionally, adding items to an array through pushing may not be successful

Here is a snippet of HTML code: <select name="region-select" id="regions-select" class="form-control"> <option selected=""> </option> <option value="23">Name1</option> <option value="24">Name2</option> ...

The Best Practices section of the Chrome lighthouse report has identified an issue with properly defining the charset

I recently noticed an error in my VueJs SPA application when running a Chrome Lighthouse report. The error message indicated that the charset was not properly defined, even though I had added it to my index.html file. Below are screenshots of the issue: ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

The form's validation fails to recognize dynamically added input after the initial validation

I am currently working on a form that dynamically adds inputs. Whenever the user selects a different "supplier" from the addMaterialSupplier dropdown, a new input for the price is automatically added. The issue I'm facing is that when I click the bu ...

The Angular error TS2531 occurs when attempting to call scrollIntoView on an object that may be null

In my current Angular project, I am attempting to implement a scroll view using ViewChild by id. This is the method I have written: ngOnInit() { setTimeout(() => { if (this.router.url.includes('contact')) { ...

Create a custom loading spinner for a jQuery AJAX request

How can I add a loading indicator to my Bootstrap modal that is launched from a link? Currently, there is a 3-second delay while the AJAX query fetches data from the database. Does Twitter Bootstrap have built-in functionality for this? UPDATE: Modified J ...

Tips for stopping an accordion from toggling in Bootstrap when a user clicks on a specific section of the toggle button

I am currently utilizing bootstrap for my project. The accordion feature I have implemented is standard, but I am looking for a way to customize its behavior. Specifically, when a user clicks on elements with the class 'option', I want it to sele ...

Tips on resetting the position of a div after filtering out N other divs

Check out this code snippet. HTML Code: X.html <input type="text" id="search-criteria"/> <input type="button" id="search" value="search"/> <div class="col-sm-3"> <div class="misc"> <div class="box box-info"> ...

Ways to ensure that the $http.post api call waits for the response to be fully prepared

Below is the JavaScript code that I am using. When I click the button, it calls the function btnInitiateAPICall() which makes the first API call to get the number of users. However, my code does not wait for the first API call to finish before moving on ...

`Incorporating JavaScript for Menu Navigation on the Homepage: Challenges Ahead`

I am attempting to modify the HTML link within the Javascript on the thank you page, but my attempts to change all respective pages' HTML links to index.html/javascript:goTo(XXXX) have been unsuccessful. How can I successfully alter the link to conne ...

What is the best way to access a variable from a class in ES6?

Hey there, I'm having trouble accessing the variable from the KeyCodeClass. Let me walk you through what I've tried so far: Attempt 1 class KeyCodeClass1 { constructor() { this.space; } KeyDown(e) { if (e.keyCode == 3 ...

Angular HTTP client implementation with retry logic using alternative access token

Dealing with access tokens and refresh tokens for multiple APIs can be tricky. The challenge arises when an access token expires and needs to be updated without disrupting the functionality of the application. The current solution involves manually updati ...