Ways to observe and track modifications in fresh data produced within a vue component

I have encountered an issue with data manipulation in my Vue component. When I click on a checkbox, changes in the generated data are not reflected. However, when I click a button that already has existing data, changes are made successfully. Can someone please explain why this happens? Is there a solution to this problem?

Below is the code snippet:

JavaScript

Vue.component('fighters', {
    template: '#fighters-template',
  data() {
    return {
      items: [
        { name: 'Ryu' },
        { name: 'Ken' },
        { name: 'Akuma' }
      ],
      msg: 'hi'
    }
  },
  methods: {
    newData() {
        this.items.forEach(item => {
        item.id = Math.random().toString(36).substr(2, 9);
        item.game = 'Street Figther';
        item.show = false;
      });
      this.items.push()
    },
    greeting() {
        this.msg = 'hola'
    }
  }
});

new Vue({
    el: '#app'
})

HTML

<main id="app">
  <fighters></fighters>
</main>

<template id="fighters-template">
  <div class="o-container--sm u-my1">
    <ul>
      <li v-for="item in items">
      <input type="checkbox" v-model="item.show">
      {{ item.name }}</li>
    </ul>
    <button class="c-button c-button--primary" @click="newData()">New Data</button>
    <h2>{{ msg }}</h2>
    <button class="c-button c-button--primary" @click="greeting()">Greeting</button>
    <hr>
    <pre>{{ items }}</pre>

  </div>
</template>

For live code demo, visit: https://jsfiddle.net/cqx12a00/1/

Appreciate any insights you can provide. Thank you!

Answer №1

Your checkboxes are not reactive because the show variables they are bound to have not been declared. Vue does not detect updates unless these variables are initialized properly.

To fix this issue, you should initialize your data like this:

items: [
    { name: 'Ryu', show: false },
    { name: 'Ken', show: false },
    { name: 'Akuma', show: false }
]

Although using newData may seem like a solution by assigning a show property to each item, Vue cannot detect added properties without proper initialization. By setting up your data as shown above, the assignment will be reactive.

If you need to add a new reactive property to an object, remember to use Vue.set.

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

Avoid using the `target` attribute for `onclick` in Material UI components with React

Here is my current situation: The material UI component does not target my attribute on click. I am using the following button: <FlatButton containerElement="button" className="selectedNumberOfPeopleButton" onClick={this.selectedNumberOfPeople ...

Exploring the world of functional programming within nested arrays

I have been shifting towards functional programming over imperative programming recently. Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective? Here is the imperat ...

The Medusa Gatsby Ecommerce Server appears to encounter an issue when trying to run yarn start

I'm a beginner when it comes to gatsby. I'm attempting to launch the server using yarn start after running yarn install, but an error occurs stating /bin/sh: 1: /home/philip/Desktop/JS: not found. It seems to be pointing to a different directory. ...

Invoke a JavaScript function in the Codebehind file using a Button's click event

I am trying to trigger the 'Onclientclick' function after a condition is checked in a button click event. However, I am facing issues with it not working as expected. Any assistance on this matter would be greatly appreciated. Thank you in advanc ...

Need assistance with filling the space between two vertical lines on a chart using the chartjs library?

Can someone help me figure out how to fill the area between two line graphs using chartjs? I know how to do it when one line is on top of the other, but I'm struggling with getting the area between two lines that are side by side. For example, I&apos ...

How to retrieve attributes of a model from a related model in Sails.js

Currently, I am utilizing the beta version(v0.10.0-rc3) of Sails.js and have updated the database adapter to PostgreSQL in order to enable associations via the Waterline ORM. My main focus is on creating a role-based user model for authorization based on d ...

JavaScript function is not callable

Currently facing a strange issue or maybe it's just me missing something obvious. I've searched for the error but couldn't find the right solution. I am attempting to execute some Javascript code when the key "/" is pressed in a text box. ...

Using the functionalities of the parent component

Exploring Base.vue <template><div>{{ name }}</div></template> <script> export default { data() { return {name: 'Example Component'}; } }; </script> And introducing Extended.vue: <script> ...

Ways to repair the error message: "Unable to access property 'clientWidth' of undefined"

Whenever I resize the window, I encounter an error stating "Cannot read property 'clientWidth' of null". It appears to be related to the fact that the ref is null. Do you have any suggestions on how to troubleshoot this issue? import React, { us ...

Tips for adding a new variable and its value to an existing object at the end

[{ date="4/7/2012", username="dealcloud", user_id=304378189, location="New York"}, { date="4/7/2012", username="rizwanharun", user_id=18932327, location="Los Angeles"}, { date="4/7/2012", username="aimtoendhunger", user_id=12 ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

My initial experience with Stored Procedures

I am venturing into a new realm of Stored Procedures and I find myself in need of guidance on how to handle params within a Node model. The database experts have provided me with the following: USE [Some_Dev] GO DECLARE @return_value int, @Au ...

Personalize the appearance of dynamically generated DIV elements

This script generates a random number of squares (ranging from 20 to 40) and adds text to each square. The script then calculates the width of each square so that they all fit in a single row. Here is the code snippet: var quantity = Math.floor(Math.ran ...

I'm curious, who's in charge of determining the height and width in Chrome dev-tools?

There are moments when I feel overwhelmed, struggling to identify the culprit behind certain property values in elements. It can be quite a challenge to pinpoint the source of the issue. Does anyone have any tips for approaching a situation where you arri ...

Designing a unique modal, unexpectedly encountering a white border surrounding the custom modal

I am trying to create a welcome modal that I can import into my MainScreen.js file and integrate it there. However, no matter how I style the modal, a white surface always appears around it despite my attempts to make it look like a "popup window". Below i ...

What is the best way to reference an object within the Vue data as the value of an item?

If I wanted to incorporate the {{ $t('index-p1') }} value within the title property, how would I do so? items: [ { icon: 'mdi-apps', title: 'Welcome', to: '/' }, For int ...

Combining data types in TypeScript (incorporating new keys into an existing keyof type)

If I have a typescript type with keys: const anObject = {value1: '1', value2: '2', value3: '3'} type objectKeys = keyof typeof anObject and I want to add additional keys to the type without manually defining them, how can I ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...

Numerous Bourbon Refill Opportunities

I'm currently working on a project that involves using the Bourbon Refills UI elements and I have a particular query related to modals. Specifically, I need to have multiple modals open simultaneously in a certain scenario. Here's what I'm ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...