Vue.js动态添加按钮绑定onclick自定义函数失效问题求助
问题分析与解决方案
核心问题
你当前的实现完全违背了Vue的数据驱动原则,导致事件绑定失效:
- 用
innerHTML动态插入的v-on:click不会被Vue编译——Vue仅在组件初始化时解析模板指令,后续手动插入的HTML不会被处理。 - 通过
setAttribute('onclick', 'myFunction')绑定事件时,myFunction是全局作用域函数,但你定义的myFunction属于组件实例的methods,全局作用域无法访问,因此点击无响应。
正确实现方式
改用Vue响应式数据渲染表格,彻底抛弃手动DOM操作:
- 在组件data中添加数组存储接口返回的案例数据
- 模板中用
v-for循环生成表格行,直接绑定Vue事件
修改后的完整代码:
<template> <div class="Main"> <component :is="checkJWT()"/> <h3>{{organization_name}}</h3> <div> <table id="workflowTable" style="width:100%"> <tr> <th>ID</th> <th>Title</th> <th>操作</th> </tr> <!-- 用v-for循环渲染数据行 --> <tr v-for="rec in cases" :key="rec.id"> <td style="border: 1px solid;text-align:center">{{rec.id}}</td> <td style="border: 1px solid;text-align:center">{{rec.title}}</td> <td><button @click="myFunction(rec.id)">View</button></td> </tr> </table> </div> </div> </template> <script> import jwt_decode from "jwt-decode"; export default{ data () { return { organization_name: "", cases: [] // 新增数组存储案例数据 } }, methods: { checkJWT: function(){ var access_token = document.cookie.split("=")[1]; var decoded = jwt_decode(access_token) this.organization_name = decoded.azp this.getCaseInformation(this.organization_name) }, getCaseInformation: async function(){ fetch('http://localhost:3000/workflow-page/' + this.organization_name, { method: "GET", headers: { "Content-Type": "application/json", "Authorization": "Bearer " + document.cookie.split("=")[1] } }) .then(response => response.json()) .then(result => { // 直接把结果赋值给响应式数组,Vue会自动渲染表格 this.cases = result; }) }, myFunction(id){ console.log("点击了ID为", id, "的按钮") } } } </script>
关键改动说明
- 新增
cases数组作为响应式数据源,接口返回数据直接赋值给它,Vue会自动触发视图更新 - 模板中用
v-for="rec in cases"循环生成表格行,:key="rec.id"是Vue列表渲染的必填项,用于跟踪节点身份 - 按钮点击事件直接用
@click="myFunction(rec.id)"绑定,这里的myFunction是组件实例的methods,可正常触发 - 移除所有手动DOM操作代码(
innerHTML、setAttribute、makeClickable方法),完全遵循Vue开发范式
额外优化点
- 移除请求头中不必要的
Access-Control-*头(这些是服务器端配置项,前端请求无需携带) - 将
Content-Type改为application/json,符合REST接口常规配置 myFunction增加id参数,可区分点击的是哪一行按钮
内容的提问来源于stack exchange,提问作者doozy
相关产品推荐
相关产品推荐

