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

Navigate-to-pattern Utilize regular expression to match the pathway

As I load the page, I am dynamically adding child components. However, when I try to add child routes in the OnCreated method of the parent component, the page fails to work properly upon refreshing. Instead, I have decided to parse the page templates as ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. In contrast, highlighted near the red arrows is my attempt at using Winston to ...

Encountering an issue with inability to resolve the 'react-navigation-stack' module. Still seeking a solution to this problem

Having trouble with my react navigation in react native. I've already added npm react-navigation-stack and also npm install --save react-native-gesture-handler react-native-reanimated react-native-screens. The error message I'm getting is: Unab ...

Changing the text color of the Vuetify Table header is a simple way to customize the

I am currently working on a Vuetify table with the class condition-table. I have applied the following CSS styling: .condition-table { background-color: #e1f5fe70; } The styling seems to work fine so far. However, when I added this additional CSS: .co ...

The rows-per-page menu option in Vuetify suddenly vanishes

I'm currently working on incorporating a v-data-table inside a v-card, you can view the code in this CodePen snippet: https://codepen.io/benwasin97/pen/eYveZGL <v-data-table :headers="headers" :items="items" ...

Issue: "The argument provided must be a specific string, not a string or an array of strings."

Currently, I am tackling a Vue project that incorporates TypeScript and axios for handling API requests. While working on the Reset Password component, the resetPassword function within the auth.ts file appears as follows: resetPassword(password1: string, ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...

What methods can I use to sort content by its rating?

I am embarking on my inaugural project and attempting to construct a product filtering system. So far, I have successfully implemented search and category filters; however, configuring the rating filter has proven to be challenging. Here is an excerpt of ...

Eliminating clutter in bespoke event handlers - eliminating the necessity for the 'event' parameter

I have a project where I am creating objects that will trigger custom events, and I am using jQuery's bind and trigger functions to handle this task. Here is an example of how I am implementing it: function MyObject() { var _this = this; th ...

Executing a NodeJS function from a JavaScript function

I am working on a project involving Firebase and I am looking to connect a server-side function that can send an email to the client-side script. Below is my server-side index.js file: const functions = require('firebase-functions'); var nodema ...

Error message encountered when attempting to rotate an object in three.js: "Object is undefined"

Experiencing an "Undefined Object" error while attempting to rotate an object using three.js. Here is a snippet of the code in question: var object; function render() { renderer.render(scene, camera); } function animate() { object.rotation.x + ...

HTML embedded content is not appearing on the React webpage

I'm attempting to incorporate GoFundMe donation buttons into a React page, but unfortunately, they aren't displaying on the screen. const Donation = () => { return ( <div> <div className="gfm-embed" d ...

Output each element of an array in Vuejs2 with a line break between each

I am currently working with vuejs2 and have a select tag where a person is selected, with their address properties directly bound to the element. I need to display the address of the selected person. I attempted to use an array in order to print out the el ...

Errors can arise in Discord.js when encountering "undefined" before the first array object in an embed

I am currently in the process of creating a Discord bot command that allows users to construct their own city. I am encountering an issue with a list command that is supposed to display all the roads and places built within the city. However, each list kee ...

node.js: The Yahoo weather jQuery plugin fails to display any data

After successfully implementing node.js with jQuery and the plugin from , I now aim to utilize the weather data for a different purpose rather than directly inserting it into the HTML. However, I am encountering difficulties in accessing or displaying the ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...

What is the best way to add permissions to each role in JavaScript?

I have been attempting to dynamically add data to an HTML table using JavaScript. The data consists of roles and their corresponding permissions, which are retrieved using Laravel's ORM. I have tried utilizing a nested each jQuery function to append t ...

The lookAt method in THREE.js is not functioning properly when called after the rendering process

The code snippet below seems to be causing some issues. It requires jquery and three.js to function properly. The problematic lines are as follows: // change the view so looking at the top of the airplane views[1].camera.position.set( 0,5,0 ); views[1].ca ...

display and conceal elements and refresh action

Can anyone help me with a function to hide and show a div? function toggledDivVisibility(divName) { if (divName.is(':hidden')) { var hiddenDiv = document.getElementById("filter"); hiddenDiv.style.display = 'block&a ...