
本文介绍在 vuetify + nuxt 应用中,当表格单元格内容(textcontent)发生变化时,自动触发动画效果的可靠实现方案,重点使用 mutationobserver 监听 dom 变更,并配合 css 动画完成无侵入式视觉反馈。
本文介绍在 vuetify + nuxt 应用中,当表格单元格内容(textcontent)发生变化时,自动触发动画效果的可靠实现方案,重点使用 mutationobserver 监听 dom 变更,并配合 css 动画完成无侵入式视觉反馈。
在 Vue 生态中,直接监听
推荐采用 MutationObserver 这一现代 Web API:它专为响应 DOM 结构或内容变化而设计,轻量、高效、且与 Vue 的响应式更新解耦,完美适配 Vuetify 表格这类由数据驱动渲染的场景。
✅ 正确实现步骤
- 选择目标单元格:使用 document.querySelectorAll(‘tbody td’) 精准定位所有数据单元格(避免监听表头 th 或其他无关节点);
- 创建观察器实例:监听 childList 类型变更(textContent 改变会触发该类型);
- 添加/清理动画类:检测到变更后立即添加 .is-changed 类触发 CSS 动画,并在 animationend 后自动移除,确保动画可重复触发;
- 绑定观察器:对每个
单独调用 observe(),启用 { childList: true } 选项。 以下是完整可运行的示例代码(兼容 Nuxt 3 / Vue 3 组合式 API,建议在 onMounted 中执行):
// 在 setup() 或 onMounted() 中调用 onMounted(() => { const contentsObserver = new MutationObserver((mutations) => { mutations.forEach((mu) => { if (mu.type === 'childList') { mu.target.classList.add('is-changed'); mu.target.addEventListener( 'animationend', () => mu.target.classList.remove('is-changed'), { once: true } ); } }); }); // 仅观察 tbody 内的 td(排除表头、分页栏等干扰) const tdCells = document.querySelectorAll('tbody td'); tdCells.forEach((td) => { contentsObserver.observe(td, { childList: true }); }); // 清理函数(可选,用于组件卸载时释放资源) onUnmounted(() => { tdCells.forEach((td) => contentsObserver.unobserve(td)); contentsObserver.disconnect(); }); });配套 CSS 动画定义(建议放入全局样式或
立即学习“前端免费学习笔记(深入)”;
td, th { padding: 0.5rem 1rem; font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; font-size: 0.875rem; line-height: 1.5; } .is-changed { animation: highlight 0.6s ease-out; } @keyframes highlight { 0% { background-color: #e6f7ff; } 50% { background-color: #91d5ff; } 100% { background-color: #e6f7ff; } }? 关键注意事项:
此方法不依赖 Vue 特定生命周期或 Vuetify 内部实现,稳定、跨框架、易于复用,是为动态表格提供视觉反馈的专业级实践方案。