Exploring VueJs 2.0: Iterating through components and updating properties

Searching for the optimal method to handle looping components has been my current focus. Below is an example of my coding dilemma.

What I am attempting to accomplish is having payments data in my main component loop into child components.

<tr v-for="payment in payments"
is="component-payment-item"
:payment="payment
v-on:toggleReported="togglePaymentReported"">
 </tr>

Whenever a child component needs to mark a payment as reported, it sends an event back up to the parent component. To tackle this issue, I coded the following solution:

togglePaymentReported(payment) {
    payment.reported = ! payment.reported;
}

Although the function executes properly, the changes do not reflect in the child component. I have considered directly modifying the payment within the array, assuming it would be passed by reference and updated in the child component as well.

In vue 1.0, adjusting the child component itself was feasible but not recommended and no longer supported in vue 2.0. What approach should I adopt in this scenario?

Answer №1

Make sure to include the current payment as an argument in your togglePaymentReported method.

pb = Vue.extend({
  template: '#paybutton-template',
  props: ['payment'],
  methods: {
    toggle: function() {
      this.$emit('toggle');
    }
  }
});

vm = new Vue({
  el: '#app',
  components: {
    'payment-button': pb
  },
  data: {
    payments: []
  },
  methods: {
    handleToggle: function(payment) {
      payment.paid = !payment.paid;
    }
  },
  mounted: function() {
    // Simulating setting from ajax
    setTimeout(() => {
      this.payments = [{
        id: 1,
        paid: false
      }, {
        id: 2,
        paid: false
      }];
    }, 800);
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js"></script>
<div id="app">
  <payment-button v-for="payment in payments" :payment="payment" v-on:toggle="handleToggle(payment)"></payment-button>
</div>

<template id="paybutton-template">
  <div>
    {{payment.id}}: {{payment.paid}}
    <button @click="toggle">Pay</button>
  </div>
</template>

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

Using sql.js to import CSV files into SQLite databases

Is it possible to import a CSV file into a SQLite database using JavaScript instead of the command line? I am currently utilizing the sql.js library to work with SQLite in Javascript. I appreciate any help or suggestions on how to accomplish this task. Th ...

Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> Is there a way I can mak ...

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

Navigating to a different URL in a remoteMethod with Loopback and Express

Can anyone provide any guidance on how to redirect to a URL within a model function or remoteMethod? I've been struggling to find documentation on this. Here is the code snippet for reference: Model Function (Exposes /catch endpoint) Form.catch = func ...

Guidelines for setting up Kendo notifications using an angularjs service

I have successfully defined the Kendo notification in my Angular service. However, when I try to use it with the line uiService.notify.error("You missed some required fields.");, I am getting an error that says "Cannot read property 'show' of nul ...

Tips for stopping a click from going through a fixed element to the one in the background

My website features a fixed positioned header with a search box, overlaying content below it (thanks to the higher z-index). When I click on the search box, an event handler is triggered. However, the click response also passes through the header to the ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

Is JavaScript responsible for creating threads for non-blocking AJAX requests?

It is widely believed that JavaScript operates on a single-threaded model, but it has the ability to run asynchronously. One intriguing aspect is how this single-threaded model manages non-blocking AJAX requests. Consider a scenario where a non-blocking A ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Creating a comparison display using ng-repeat

I have a JSON file that contains revision and history information about a modified entity, including its old and new values. The diff is generated using the jsondiffpatch library and I have parsed it further to create the final JSON format for rendering. ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

Is there a way to transform an Array or Object into a new Object mapping?

When using the map method in JavaScript, it typically returns an Array. However, there are instances where I would like to create an Object instead. Is there a built-in way or a simple and efficient implementation to achieve this? Solutions using jQuery ar ...

Ways to prevent event bubbling in the case of a checkbox input alteration?

Description I am looking to create a table component with checkboxes, but I am facing an issue. Whenever I click on a checkbox, the click event is also triggered for the table row and cell containing the checkbox, which is not what I want. I have tried us ...

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error ...

Experience the power of ReactJS as you utilize the componentDidMount lifecycle method to fetch data

Currently, I am in the process of learning how to utilize ReactJS, Spotify API, and Promises. My goal is to retrieve top albums from musicians on Spotify and play a 30-second snippet of their tracks. I have decided to work with a Spotify package known as ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

Vuetify Slide Groups when clicked on, will toggle on and off

Referencing the most recent example found on this page: https://vuetifyjs.com/en/components/slide-groups I am currently attempting to comprehend the mechanics behind the following code snippet: <v-slide-item v-for="n in 15" :key="n" v-slot:de ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...