Why isn't v-model functioning properly in Vue?

In my current project involving an API, I encountered a problem. I utilized axios to fetch data from the API, which returned a JSON array. Each array item had a radio value that I appended to it. Despite attempting to use v-model to track changes in the radio values, it was not functioning as expected. I even displayed the selected value below the radio element for debugging purposes. Below is a snippet resembling my actual project code:

var app2 = new Vue({
  el: '#app-2',
  data: {
    list: null
  },
  created: function () {
    var json = [{id:1,name:"B"},{id:2,name:"D"}]
    this.list = json
    this.list.forEach(function (v) {
       v.options = [{ text: 'pacageA' , value: 1},{text: 'pagckaeB',value:2}]
       v.selected = null
    })
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e181b0b2e5c405b405f5d">[email protected]</a>/dist/vue.js"></script>
<div id="app-2">
  <div v-for="l,ix in list">
     <div v-for="o in l.options">
      <input type="radio" v-model="l.selected" :name="'test'+ix" :value="o.value">
      </div>
          <h3>{{l.selected}}</h3>
  </div>
</div>

Answer №1

Your issue lies in the reactivity of your code. To ensure that Vue recognizes the new object properties added to your list, consider using Vue.set. Here's an example:

Vue.set(v, 'options', [{ text: 'packageA' , value: 1},{text: 'packageB',value:2}])
Vue.set(v, 'selected', null)

Alternatively, as suggested below, make sure to "complete all modifications to json before assigning it to this.list".

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

Troubleshooting Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

The resizing issue persists with Angularjs charts

I have recently developed a small web application using AngularJS and I have implemented two charts from the AngularJS library - a bar chart and a pie chart. Although both charts are rendering correctly, they are not resizing properly as the display size c ...

"Encountering errors during npm installation due to a failed preinstall

Having identified security vulnerabilities for knexnest > knex > minimist, I encountered an issue where the minimist version did not update using npm audit fix or a simple npm update. Following the steps outlined in this informative article resolved ...

Updating from Babel 6 to Babel 7 resulted in an error: Unexpected token detected (spread operator)

I recently made the transition from Babel 6 to Babel 7 but encountered some errors that I am struggling to resolve. During the migration, I came across an issue where I received the following error even though I was using @babel/plugin-proposal-object-res ...

Issue with setTimeout() function not being triggered within a VueJS method

I am currently developing an application that allows a user to reset or shutdown a particular server. I am focused on creating the interface and ensuring that the user receives appropriate messages about the actions being taken. My approach involves displa ...

Is there a way to have multiple app.post functions for the same route using express()?

I'm currently exploring the idea of incorporating multiple app.post functions in my project. Specifically, I have a client-side JavaScript function that sends a request to the server-side JavaScript to add content to a database using the app.post func ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

Sending an object as a prop in React component

I have a function class: function TopicBox({topicName, article1}) { return ( <div className="TopicBox"> <h1>{topicName}</h1> <div className="topicDivider" /> <Ar ...

Display the appropriate selection choices based on the knockout condition

In my HTML page, there is a dropdown with certain conditions that determine which options should be rendered in the select element. My attempt at achieving this: <select> <!-- ko if: condition() --> <option value="1">1& ...

React fails to recognize the key prop

When creating a list of TSX elements, I utilized the following code: this.productsModel = this.state.products.map(o => ( <Grid.Column key> However, I encountered a warning from React: Warning: Each child in a list should have ...

AngularJS $log - display line numbers

When using angularjs $log in chrome, it displays the line as: angular.js:9037. I'm looking to have the line number where I actually call this method shown instead. (Displaying my js name and the correct line). Is there a way to achieve this since Angu ...

How to change the state using an object as an argument in the useState hook within a function

This code uses a function component: export default function Account() { We define a constant with inputs as objects: const [state, setState] = useState({ profile: true, orders: false, returns: false, coupon: false, referrals: false, rewards: ...

Result of a callback function

Having trouble returning a value for form validation using a callback function. It's not working for me... <form action="loggedin.php" onsubmit="return test(valid)" method="post"> function test(callback) { var k = ""; var httpRequest = ...

Manipulating a textarea in jQuery by inserting a string and selecting a specific portion of it

Just as seen on SO with the B button: **bold text** Including that bold text is automatically highlighted and the cursor is placed right before the b ...

Using JSON parsing to extract an integer as the key in JavaScript

I've been searching for almost 2 hours now, but I can't seem to find anyone using an integer as the key in their json object. The structure of my json object is as follows: {"342227492064425": {"added":"2020-10-04T23: ...

The <router-link> component within a nested <router-view> does not trigger an update in the parent component

I have set up nested routing in my Vue application using <router-view>. The issue I am facing is that when I click a link component in the child component, it updates only the child component and not the parent component. Does anyone have any sugge ...

I am facing an issue with the clearTimeout function in my JavaScript code. Can anyone help

I am encountering some issues with the clearTimeout() function. The setTimeout() function is working as expected, but I want it to stop running when I close my notification. I'm not sure what is causing the problem in my function. After closing the ...

Data retrieved from a different Vue component

Is there a way to access and utilize the value of an element from one Vue component in another? As an example, I am interested in obtaining the value of a textbox from one component and applying it in another. ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

There seems to be a JSON syntax error on the website for tracking Covid-

Hi everyone, I'm currently working on a Covid-19 tracker website and facing an issue that says: 'SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' ; Being new to web development, I am unsure about what&apo ...