Vue 3实现点击按钮添加表格新行的问题求助
解决方案
核心思路
要实现点击按钮添加原数组的新元素到展示列表,只需在addRandom方法中从contactList里挑选未展示的元素,添加到contactListed数组即可——Vue会自动响应数组变化,更新表格渲染。
具体修改步骤
添加
addRandom方法
在methods中新增方法,实现随机挑选未展示的联系人并添加到展示列表:addRandom() { // 筛选出还没在展示列表里的联系人 const unshownContacts = this.contactList.filter(contact => !this.contactListed.includes(contact)); // 如果所有联系人都已展示,直接返回 if (unshownContacts.length === 0) return; // 随机选一个未展示的联系人 const randomIdx = Math.floor(Math.random() * unshownContacts.length); const pickedContact = unshownContacts[randomIdx]; // 添加到展示数组 this.contactListed.push(pickedContact); }优化
wonAward方法(可选)
原方法里的判断逻辑重复,可简化为更简洁的写法:wonAward(element) { return element ? "winner" : ""; }
修改后的完整代码
<template> <h1 class="display-1 text-primary">Contacts</h1> <button type="button" class="btn btn-outline-primary btn-lg" @click="addRandom">Add random</button> <div class="container container__pos"> <table class="table table-hover"> <thead> <tr> <th class="col col__style">Picture</th> <th class="col col__style">Name</th> <th class="col col__style">Popularity</th> <th class="col col__style">Won an Oscar</th> <th class="col col__style">Won an Emmy</th> </tr> </thead> <tbody> <tr v-for="(element, index) of contactListed" :key="index"> <td scope="row"> <img :src="element.pictureUrl" :alt="element.name + ` image`" class="image" /> </td> <td> {{ element.name }}</td> <td>{{ element.popularity }}</td> <td>{{ wonAward(element.wonOscar) }}</td> <td>{{ wonAward(element.wonEmmy) }}</td> </tr> </tbody> </table> </div> </template> <script> import contacts from "./contacts.json"; export default { data() { return { contactList: contacts, contactListed: contacts.slice(0, 5), }; }, methods: { wonAward(element) { return element ? "winner" : ""; }, addRandom() { const unshownContacts = this.contactList.filter(contact => !this.contactListed.includes(contact)); if (unshownContacts.length === 0) return; const randomIdx = Math.floor(Math.random() * unshownContacts.length); const pickedContact = unshownContacts[randomIdx]; this.contactListed.push(pickedContact); } }, }; </script>
关键说明
- Vue会监听数组的变更方法(比如
push、pop、splice等),所以直接用push添加元素,表格会自动新增一行。 - 用
filter筛选未展示元素,避免重复添加同一个联系人;如果允许重复,可直接从contactList里随机选元素push。
内容的提问来源于stack exchange,提问作者alvarx
相关产品推荐
相关产品推荐

