Home > database >  Add html element with an event in Vue3
Add html element with an event in Vue3

Time:12-13

I need to add series of table lines in VueJS3, each one with a button, and each button need to call a function. But the event doesn't work, neither the Firefox Tools doesn't show the event.

HTML

<table id='tableFields' class='table' v-html='fields'>
</table>

Javascript component (snippet)

for (let tablename of this.tables) {
            this.fields  = "<tr><td><button @click=\"setBaseTable('"   tablename   "')\">"   tablename   "</button></td></tr>";
}
...
methods: {
    setBaseTable: function (name) {
      this.baseTable = name;
      alert(name)
      console.log(name)
    },
}

It creates the right HTML, but it doesn't add the event to the button.

<table id="tableFields" >
<tbody>
<tr><td><button @click="setBaseTable('active_time')">active_time</button></td></tr>
<tr><td><button @click="setBaseTable('active_worktime')">active_worktime</button></td></tr>
</tbody>
</table>

There is no error in console. The event simply doesn't work.

CodePudding user response:

Adding HTML manually can't work. You have to use v-for macro. Something like that should work.

<table id='tableFields' class='table' v-html='fields'>
  <tr v-for="table in tables">
    <td>
      <button @click="setBaseTable(table)">{{ table }}</button>
    </td>
  </tr>
</table>
  • Related