mikelbring mikelbring - 19 days ago 15x
Javascript Question

VueJs 2.0 Looping components and changing props

I am trying to figure out what is the best way to handle looping components. Here is some example code.

This is kinda what I am trying to do. My main component has payments data which loops into child components.

<tr v-for="payment in payments"

My child component when it want's to mark a payment as reported, it just sends up an event. Which the parent component captures. So in the parent component I try this.

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

I know for sure this fires, however that change never goes back down to the child component. I don't know if this is the best way to handle this. The other way I thought is to actually find that payment in the array and change it that way but I figured it would be passed by reference and propagate down to the child component.

In vue 1.0 I would just change it on the child component it self. I know that is frowned upon and just not possible in vue2.0. What is the best practice here?


You need to pass the current payment to your togglePaymentReported method for it to receive it as an argument.

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

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>

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