Home > OS >  Vue.js method calls on string in tabledata
Vue.js method calls on string in tabledata

Time:11-11

Have been task to have a look at a Vue app (gulp....react dev here) for a colleague that left the company. However it is built with a string that renders the table data in a for loop such as this:

      var table = "";
      for (var i = 0; i < companies.length; i  ) {
        table  = "<tr>";
        table  = `<td id="checkUpdateBox"><input onClick=${this.updateSomeCompanies(companies[i].id)}
         type="checkbox"/></td>`;
        table  = `<td>${companies[i].id}</td>`;
        table  = `<td>${companies[i].name}</td>`;
        table  = `<td>${companies[i].custom_fields.seno}</td>`;
        table  = `<td>${companies[i].created_at}</td>`;
        table  = "</tr>";
      }
 methods: {
    updateSomeCompanies(id) {
      console.log(id);
    },

// next method and so on

Am trying to do an update based on the id of the company. Right now, I am just console.logging the id on the method updateSomeCompanies.

However, when the page is loading I am getting the id of the company in the console even though the checkbox haven't been clicked, how come it works like this, is the strange string loop that build the tabledata or am something strange in the code above?

Furthermore, when clicking the checkbox nothing happens?

Have tried with the v-on:clicked and the @Click (same results as above).
Console.logs all of the id's then checkbox do not work.

CodePudding user response:

Suggestions :

  • As you are using Vue.js then no need to use Vanilla JS to create a table. You can do it dynamically in the template itself.
  • Use @click/v-on:click directive of Vue to trigger the click event instead of JS onClick.

Live Demo :

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    companies: [{
      id: 1,
      name: 'Alpha',
      created_at: 'test'
    }, {
      id: 2,
      name: 'Beta',
      created_at: 'test'
    }, {
      id: 3,
      name: 'Gamma',
      created_at: 'test'
    }]
  },
  methods: {
    updateSomeCompanies(id) {
        console.log(id);
    }
  }
})
table, th, td {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <tr>
      <th></th>
      <th>ID</th>
      <th>Name</th>
      <th>Created At</th>
    </tr>
    <tr v-for="company in companies" :key="company.id">
      <td id="checkUpdateBox">
        <input v-on:click="updateSomeCompanies(company.id)" type="checkbox"/>
      </td>
      <td>{{ company.id }}</td>
      <td>{{ company.name }}</td>
      <td>{{ company.created_at }}</td>
    </tr>
  </table>
</div>

  • Related