How do I target a dynamic second table in vue2

Viewed 21

I am using v-for in Nuxt vue2 to create a table with a table with in it but cant find any way to target the second table. This is the HTML I am using and the command lines I am using to target the data. The first table appears to work but I have tried everything I can think of to target the second table. Hopefully someone can show me how to do it and more importantly explain why there is a problem with the inner table.

<template>
  <div>
    Working with the DOM Vue2
    <table ref="table1">
      <tr v-for="index in 5" :key="index">
        <th>Company{{ index }}</th>
        <th>
          <table ref="tableChild">
            <tr v-for="index in 2" :key="index">
              <th>Inner table Line{{ index }}</th>
            </tr>
          </table>
        </th>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  mounted() {
    //-------- targeting the two tables --------------
    console.log("table1:", this.$refs.table1);
    console.log("table1-all children:", this.$refs["table1"].children);
    console.log("table1-all children0:", this.$refs["table1"].children[0]);
    console.log("tableChild:", this.$refs.tableChild);
    console.log("tableChild-all children:", this.$refs["tableChild"].children);
    console.log("tableChild-all children0:", this.$refs["tableChild"].children[0]);
  }
}
</script>

<style>
</style>
1 Answers

To access the inner table data by using ref. Here you go :

this.$refs.tableChild[0].children[0]

Live Demo :

new Vue({
  el: '#app',
  mounted() {
    console.log("table1:", this.$refs.tableChild[0].children[0].innerText);
  }
})
table, tr, th {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table ref="table1">
    <tr v-for="index in 5" :key="index">
      <th>Company{{ index }}</th>
      <th>
        <table ref="tableChild">
          <tr v-for="index in 2" :key="index">
            <th>Inner table Line{{ index }}</th>
          </tr>
        </table>
      </th>
    </tr>
  </table>
</div>

Related