vue实现动态用户表格
Vue 实现动态用户表格
数据准备与响应式绑定
在 Vue 中实现动态用户表格,需先定义响应式数据。通过 data 或 ref(Composition API)存储用户数据数组,确保数据变化能触发视图更新。例如:
// Options API
data() {
return {
users: [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
]
};
}
// Composition API
const users = ref([
{ id: 1, name: 'Alice', email: 'alice@example.com' }
]);
表格渲染与动态列
使用 v-for 指令循环渲染表格行和列。动态列可通过遍历对象的键实现灵活性:
<table>
<thead>
<tr>
<th v-for="(value, key) in users[0]" :key="key">{{ key }}</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td v-for="(value, key) in user" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
动态操作功能
添加编辑、删除等操作按钮,通过方法修改数据。例如删除功能:
methods: {
deleteUser(id) {
this.users = this.users.filter(user => user.id !== id);
}
}
<td>
<button @click="deleteUser(user.id)">Delete</button>
</td>
表单添加新用户
通过表单绑定新增用户数据,使用 v-model 实现双向绑定:
<input v-model="newUser.name" placeholder="Name">
<input v-model="newUser.email" placeholder="Email">
<button @click="addUser">Add User</button>
data() {
return {
newUser: { id: null, name: '', email: '' }
};
},
methods: {
addUser() {
this.newUser.id = this.users.length + 1;
this.users.push({ ...this.newUser });
this.newUser = { id: null, name: '', email: '' };
}
}
完整组件示例
整合上述代码的完整组件示例:
<template>
<div>
<table>
<thead>
<tr>
<th v-for="(value, key) in users[0]" :key="key">{{ key }}</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td v-for="(value, key) in user" :key="key">{{ value }}</td>
<td>
<button @click="deleteUser(user.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<div>
<input v-model="newUser.name" placeholder="Name">
<input v-model="newUser.email" placeholder="Email">
<button @click="addUser">Add User</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
users: [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
],
newUser: { id: null, name: '', email: '' }
};
},
methods: {
deleteUser(id) {
this.users = this.users.filter(user => user.id !== id);
},
addUser() {
this.newUser.id = this.users.length + 1;
this.users.push({ ...this.newUser });
this.newUser = { id: null, name: '', email: '' };
}
}
};
</script>
通过以上步骤,可实现一个具备动态渲染、增删功能的用户表格。根据需求可扩展排序、分页或编辑功能。







