
本教程详细介绍了在 vue 3 应用中,如何通过管理组件的响应式状态,实现表格(
在前端开发中,表格是展示数据的重要组件。当表格中的某些文本内容较长时,我们通常会选择截断显示,并在用户需要时提供查看完整内容的功能。本文将指导您如何在 Vue 3 中,通过点击表格单元格(
Vue 3 遵循数据驱动视图的原则。直接在 @click 事件中尝试修改 v-text 的值是无效的,因为 v-text 是一个指令,它绑定到组件的响应式数据。要实现动态切换,我们需要:
我们将以一个展示邮件主题的表格为例,演示如何实现点击单元格切换显示截断主题和完整主题的功能。
首先,在您的 Vue 组件的
立即学习“前端免费学习笔记(深入)”;
<script setup>
import { ref } from 'vue';
// 假设 emails 是从某个 store 或 API 获取的邮件数据
const emails = ref({
data: [
{ id: 1, subject: '这是一封非常长的邮件主题,需要被截断显示以节省空间,方便用户快速浏览。', body: '内容1' },
{ id: 2, subject: '另一封简短的邮件主题', body: '内容2' },
// 更多邮件数据...
]
});
// 模拟 store 对象,提供获取截断和完整主题的方法
const store = {
getSubjectTruncated: (email) => {
if (!email.subject) return '';
const maxLength = 25; // 定义截断长度
return email.subject.length > maxLength ? email.subject.substring(0, maxLength) + '...' : email.subject;
},
getSubject: (email) => email.subject || ''
};
// 定义响应式状态,用于跟踪当前显示完整主题的邮件索引
const currentShownEmailIndex = ref(-1);
</script>接下来,修改您的表格模板。在 v-for 循环中,确保您能够获取到当前项的 index。然后,为需要切换文本的
<template>
<div class="email-table-container">
<h2>邮件列表</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>邮件主题</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(email, index) in emails.data" :key="email.id">
<td>{{ email.id }}</td>
<td
@click="currentShownEmailIndex = currentShownEmailIndex === index ? -1 : index"
v-text="currentShownEmailIndex === index ? store.getSubject(email) : store.getSubjectTruncated(email)"
:title="store.getSubject(email)"
class="subject-cell"
></td>
<td><button @click="alert('查看邮件详情')">详情</button></td>
</tr>
</tbody>
</table>
</div>
</template>代码解释:
<template>
<div class="email-table-container">
<h2>邮件列表</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>邮件主题</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(email, index) in emails.data" :key="email.id">
<td>{{ email.id }}</td>
<td
@click="currentShownEmailIndex = currentShownEmailIndex === index ? -1 : index"
v-text="currentShownEmailIndex === index ? store.getSubject(email) : store.getSubjectTruncated(email)"
:title="store.getSubject(email)"
class="subject-cell"
></td>
<td><button @click="alert('查看邮件详情')">详情</button></td>
</tr>
</tbody>
</table>
</div>
</template>