Rod Bell
Rod Bell

Reputation: 23

How Can I capture parent component event in an event emitted by a child event

I'm trying to create a dynamic table in Vue in two levels: child component contain the cells with 'idx' as :key, and the parent has the child components in table with 'line' as :key.

My question is: when I capture the customized event @update-cellValue, I have the idx, oldValue and newValue brought to scope, but I don't have access to the details of the parent component where the event was emitted (which line from the v-for). I mean, my intention is to have both (line, idx) and work like a matrix (2D array).

I have a workaround doing it all in one level, just using v-for directly in "child's component" , but I would like to have it separately in two different components

Child (Nested) component -> Table line containing cells

<template>
  <div >
    <tr class='center'>
      <!-- add title to the tr as prop -->
      <td 
        id='cell'
        @click="selectCellEv"
        v-for="(cell, idx) in cells" :key="idx">
      <input type=number @input="updateCellValueEv" 
        v-model.lazy.trim="cells[idx]"/>
      </td>
  </tr>
  </div>

</template>

<script>
// var editable = document.getElementById('cell');
// editable.addEventListener('input', function() {
    // console.log('Hey, somebody changed something in my text!');
// });
export default {
  name: 'CaRow',
  props: {
    cellValArr: {
      type: Array,
      required: false,
      default: () => [],
    },
    title: {
      type: String,
      default: `noNameRow`
    }
  },
  data(){
      return {
          cells: []
      }
  },

  methods: {
    updateCellValueEv(event){
      const idx = event.target.parentElement.cellIndex;
      let val = event.target.value;
      if (val === '') val = 0;
      const oldNumber = parseFloat(this.cells[idx]);
      const newNumber = parseFloat(val);
      if(!isNaN(newNumber) && !isNaN(oldNumber)){
        // console.log(`new ${newNumber}, old ${oldNumber}`)
        this.$emit('update-cellValue', idx, newNumber, oldNumber);
        this.cells[idx] = newNumber;
      }
    },
  },
  created() {    
    this.cellValArr.map((val,idx) => {
      this.cells[idx] = val;
    });
  },
}
</script> 

Parent component (will be used directly in the app)-> Table containing the child components as lines

<table class="center">
  <CaRow
  v-for="(line, idx) in table" 
  :key="idx"
  :cellValArr="table[idx]"
  @update-cellValue="updateCellVal"
  >{{line}} </CaRow>
</table>
</template>

<script>
import CaRow from './components/CaRow.vue'
export default {
  name: 'App',
  components: {
    CaRow
  },
  data(){
    return{
      table: [[1,2,3],
              [4,5,6],
              [7,8,9]],
      selectedCell: null,
    }
  },
  methods: {
    updateCellVal(idx, newValue, oldValue) {
      console.log(`cell[${idx}: New Value= ${newValue}, Old Value= ${oldValue}]`)
      // this.table[line][idx] = newValue;
      //HERE IS THE PROBLEM!!!
      //LINE IS NOT IN THIS SCOPE
    }
  },
}
</script> 

Upvotes: 2

Views: 1291

Answers (1)

tony19
tony19

Reputation: 138266

In CaRow.vue, wrap the event data into a single object:

//this.$emit('update-cellValue', idx, newNumber, oldNumber);
this.$emit('update-cellValue', { idx, newValue: newNumber, oldValue: oldNumber });

Then in the parent template, update the event handler binding to pass the line index (which is idx in this context) and $event (a special variable that stores the emitted event data):

<CaRow @update-cellValue="updateCellVal(idx, $event)">

And update the handler to receive the line index and $event:

export default {
  methods: {
    updateCellVal(line, { idx, newValue, oldValue }) {
      console.log({ line, idx, newValue, oldValue });
    }
  }
}

Vue 2 cannot detect the change when you directly set an item with the index, so you have to use this.$set():

//this.table[line][idx] = newValue;
this.$set(this.table[line], idx, newValue);

demo

Upvotes: 2

Related Questions