【问题标题】:Add html element with an event in Vue3在 Vue3 中添加带有事件的 html 元素
【发布时间】:2022-01-16 13:20:22
【问题描述】:

我需要在VueJS3中添加一系列表格行,每一个都有一个按钮,每个按钮都需要调用一个函数。但该事件不起作用,Firefox 工具也不显示该事件。

HTML

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

Javascript 组件 (sn-p)

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)
    },
}

它会创建正确的 HTML,但不会将事件添加到按钮。

<table id="tableFields" class="table">
<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>

控制台没有错误。该事件根本不起作用。

【问题讨论】:

    标签: javascript vuejs3


    【解决方案1】:

    无法手动添加 HTML。您必须使用 v-for 宏。 类似的东西应该可以工作。

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

    【讨论】:

    • 谢谢。有效。最终的解决方案使用 v-for inside HTML on template。我的 javascript sn-p 类似于“for (let table of tables) { this.tables.push(table); }
    猜你喜欢
    • 2021-03-26
    • 2022-01-27
    • 2021-06-24
    • 2020-03-06
    • 2019-11-30
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    相关资源
    最近更新 更多