0

I have an object that i am displaying dynamically on the screen with nested v-if statements. This object is displayed as a table. I want each "cell" to have a click handler that returns the indices of that exact "cell" so that i can assign a value on click.

This is my object:

const table = {
  header: ['Name', 'Runter', 'Frei', 'Hoch', 'Neiba'],
  one: { name: '1', runter: '', frei: '', hoch: '', neiba: '' },
  two: { name: '2', runter: '', frei: '', hoch: '', neiba: '' },
  three: { name: '3', runter: '', frei: '', hoch: '', neiba: '' },
};

This is my html code:

<table>
  <tr v-for="(key, object) in table" :key="object">
    <td v-for="value in key" :key="value" @click="logIt(key)">
      {{ value }}
    </td>
  </tr>
</table>

logIt is just a simple function to console.log the current cell:

function logIt(cell) {
  console.log(cell);
}

With the current configuration this is the output in chrome dev tools when i click on a cell in the row starting with 2:

{name: '2', runter: '', frei: '', hoch: '', neiba: ''}

I am trying to achieve a output like this so i can assign a value to that variable:

two.runter

If it helps here is a screenshot of the displayed table:

enter image description here

1 Answer 1

2

v-for on objects returns the object key and value 'backwards'. This means that you probably want to reverse the variable names used in your code:

<table>
  <tr v-for="(data, key) in table" :key="key">
    <!-- key = one; data = { name: '1', runter: '', frei: '', hoch: '', neiba: '' } -->
    <td v-for="(value, subkey) in data" :key="subkey" @click="logIt(key)">
      <!-- subkey = name; value = '1' -->
      {{ value }}
    </td>
  </tr>
</table>

Depending on which parameters you want, you can pass multiple parameters to logIt - e.g. @click=logIt(key, value)

Bear in mind that since the value of the first item in data - headers - is a list, you will need to take extra steps to handle this differently, probably as a thead row.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.