基于Vue.js从HTML输入框获取数据并动态生成表格
Vue.js 动态添加数据到HTML表格示例
嘿,我完全懂你折腾了好几个小时找不到头绪的挫败感!其实这个功能的核心逻辑很清晰,用Vue的v-model绑定输入、数组存数据、v-for渲染表格就能搞定,我给你写个完整的示例代码,一步步帮你理解:
完整代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Vue动态表格</title> <!-- 引入Vue 3 --> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <style> table { border-collapse: collapse; margin-top: 20px; width: 80%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } .input-group { margin-bottom: 10px; } input { margin-right: 10px; padding: 6px; } button { padding: 6px 12px; cursor: pointer; } </style> </head> <body> <div id="app"> <!-- 输入区域 --> <div class="input-group"> <input type="text" v-model="newItem.name" placeholder="输入姓名"> <input type="number" v-model="newItem.age" placeholder="输入年龄"> <input type="text" v-model="newItem.email" placeholder="输入邮箱"> <button @click="addRow">添加数据</button> </div> <!-- 动态表格 --> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>邮箱</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(item, index) in tableData" :key="index"> <td>{{ item.name }}</td> <td>{{ item.age }}</td> <td>{{ item.email }}</td> <td><button @click="deleteRow(index)">删除</button></td> </tr> </tbody> </table> </div> <script> const { createApp } = Vue; createApp({ data() { return { // 存储表格数据的数组 tableData: [], // 绑定输入框的临时对象 newItem: { name: '', age: '', email: '' } } }, methods: { addRow() { // 简单验证:确保输入不为空 if (!this.newItem.name || !this.newItem.age || !this.newItem.email) { alert('请填写完整信息!'); return; } // 将临时对象的副本添加到表格数组(避免引用问题) this.tableData.push({...this.newItem}); // 清空输入框 this.newItem = { name: '', age: '', email: '' }; }, deleteRow(index) { // 删除指定索引的行 this.tableData.splice(index, 1); } } }).mount('#app'); </script> </body> </html>
关键逻辑拆解
我把核心部分给你标出来,方便你理解:
- 输入框绑定:用
v-model="newItem.xxx"把每个输入框和data里的newItem对象属性绑定,输入内容会实时同步到Vue实例中,完全不用手动去DOM里取值——这就是Vue响应式的便利! - 添加数据方法:点击按钮触发
addRow,先做简单的非空验证,然后用push把newItem的副本(用扩展运算符{...this.newItem}避免后续修改输入框影响已添加的数据)加入tableData数组,最后清空输入框让用户可以继续录入。 - 表格渲染:用
v-for="(item, index) in tableData"循环遍历数组,把每个对象的属性渲染到表格单元格里,:key="index"是Vue要求的唯一标识(如果你的数据有唯一ID的话,用ID代替index会更稳妥)。 - 删除功能(额外附赠):我顺便加了删除行的方法,用
splice删除数组指定索引的元素,表格会自动更新——这就是响应式的好处,数组变了视图跟着同步变化!
如果你用的是Vue 2,代码结构几乎一样,只需要把createApp的部分换成new Vue({ el: '#app', ... })的写法就行。
内容的提问来源于stack exchange,提问作者Kritzencrafter
相关产品推荐
相关产品推荐

