Vue3表格:如何将整行用户对象与复选框绑定至响应式变量
实现方案
1. 调整响应式变量
将原来存储用户ID的数组,改为存储完整用户对象的数组:
<script setup> import { ref } from 'vue'; // 初始化存储选中用户对象的数组 const selectedNames = ref([]); // 搜索返回的用户列表(假设从后端获取后存入此处) const searchedUsers = ref([]); </script>
2. 修改复选框的绑定逻辑
不能直接用v-model绑定整个对象,需通过@change事件手动处理选中/取消逻辑,同时根据用户ID去重:
<template> <!-- 搜索结果表格 --> <table> <thead> <tr> <th>选择</th> <th>会员号</th> <th>姓名</th> </tr> </thead> <tbody> <tr v-for="user in searchedUsers" :key="user.id"> <td> <input type="checkbox" :checked="isUserSelected(user)" @change="toggleUserSelection(user)" /> </td> <td>{{ user.member_number }}</td> <td>{{ user.first_name }} {{ user.last_name }}</td> </tr> </tbody> </table> </template>
添加对应的处理方法:
<script setup> // 判断用户是否已被选中 const isUserSelected = (user) => { return selectedNames.value.some(item => item.id === user.id); }; // 切换用户选中状态 const toggleUserSelection = (user) => { const index = selectedNames.value.findIndex(item => item.id === user.id); if (index > -1) { // 已选中,移除该用户对象 selectedNames.value.splice(index, 1); } else { // 未选中,添加该用户对象 selectedNames.value.push(user); } }; </script>
3. 展示选中的审批人列表
直接遍历selectedNames数组,渲染所需字段:
<template> <!-- 选中的审批人列表 --> <div> <h3>Selected Approvers</h3> <ul> <li v-for="approver in selectedNames" :key="approver.id"> {{ approver.member_number }} - {{ approver.first_name }} {{ approver.last_name }} </li> </ul> </div> </template>
4. 提交表单时适配后端接口
如果后端需要接收用户ID数组,提交前将选中的用户对象转换为ID数组:
<script setup> const submitForm = () => { // 提取选中用户的ID数组 const selectedIds = selectedNames.value.map(user => user.id); // 通过Inertia提交表单(示例用useForm) form.post(route('your.submit.route'), { data: { approver_ids: selectedIds, // 其他表单字段 } }); }; </script>
内容的提问来源于stack exchange,提问作者wonder95
相关产品推荐
相关产品推荐

