Vue+TypeScript实现通知列表复选框状态同步与点击更新
Vue3 + TypeScript 通知列表复选框同步实现代码
核心实现思路
- 用TypeScript接口规范通知数据结构,保证类型安全
- 页面加载时模拟获取通知数据
- 通过
v-model直接绑定复选框到对应通知对象的isRead字段,自动完成状态同步(勾选状态跟随isRead,点击复选框自动更新isRead)
完整代码
<template> <div class="notification-container"> <h3>通知列表</h3> <table> <thead> <tr> <th>已读状态</th> <th>通知标题</th> <th>通知内容</th> </tr> </thead> <tbody> <tr v-for="(item, index) in notifications" :key="index"> <td> <input type="checkbox" v-model="item.isRead" > </td> <td>{{ item.title }}</td> <td>{{ item.content }}</td> </tr> </tbody> </table> <!-- 调试用:实时查看isRead字段变化 --> <div class="debug-info"> <h4>当前通知状态:</h4> <pre>{{ notifications }}</pre> </div> </div> </template> <script setup lang="ts"> import { ref, onMounted } from 'vue'; // 定义通知数据的TypeScript类型约束 interface Notification { id: number; title: string; content: string; isRead: boolean; } // 声明响应式通知列表 const notifications = ref<Notification[]>([]); // 模拟页面加载时获取通知数据(真实场景替换为API请求) onMounted(() => { setTimeout(() => { notifications.value = [ { id: 1, title: '系统更新通知', content: '您的系统已完成自动更新', isRead: false }, { id: 2, title: '新消息提醒', content: '您有3条未读私信', isRead: true }, { id: 3, title: '订单状态变更', content: '您的订单已发货', isRead: false } ]; }, 500); }); </script> <style scoped> .notification-container { padding: 20px; max-width: 800px; margin: 0 auto; } table { width: 100%; border-collapse: collapse; margin: 15px 0; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f5f5f5; } .debug-info { margin-top: 20px; padding: 10px; background-color: #f9f9f9; border-radius: 4px; } pre { white-space: pre-wrap; word-wrap: break-word; } </style>
关键说明
- 类型约束:通过
Notification接口明确每个通知对象的结构,避免TypeScript类型报错 - 双向绑定逻辑:复选框的
v-model="item.isRead"自动实现双向同步:- 页面渲染时,根据
item.isRead的布尔值自动勾选/取消勾选 - 点击复选框时,直接将
item.isRead更新为对应布尔值(勾选为true,取消为false)
- 页面渲染时,根据
- 数据加载:在
onMounted钩子中模拟异步加载流程,对应真实项目中从后端接口获取数据的场景
内容的提问来源于stack exchange,提问作者Trpimir
相关产品推荐
相关产品推荐

