使用 <br> 实现换行 会在页面中显示<br>
时间: 2025-09-05 21:15:35 AIGC 浏览: 9
非常抱歉,我之前的示例中没有使用 `v-html`,而是直接使用了 `{{ }}` 插值,这会导致 `<br>` 被当作文本而不是 HTML 渲染,因此你看到的是字面量 `<br>` 而不是换行。
### ✅ 正确做法:使用 `v-html` 指令来渲染 HTML 内容
---
### ✅ 修改后的完整代码:
```vue
<template>
<van-cell v-for="(item, key) in interviewScheduleList" :key="key">
<div class="interviewList">
<div
class="interviewDate"
:class="{ today: isToday(key) }"
:style="isToday(key) ? todayStyle : {}"
v-html="formatDate(key)" <!-- ✅ 使用 v-html 来渲染 HTML -->
></div>
<div v-if="item.length > 0">
<div v-for="itemCon in item" :key="itemCon.id">
<div class="interviewDetail">
<div>{{ itemCon.showName }}</div>
</div>
</div>
</div>
<div v-else>无</div>
</div>
</van-cell>
</template>
<script setup>
import { ref } from 'vue'
const today = new Date()
function isToday(dateStr) {
const inputDate = new Date(dateStr)
return (
inputDate.getDate() === today.getDate() &&
inputDate.getMonth() === today.getMonth() &&
inputDate.getFullYear() === today.getFullYear()
)
}
function formatDate(dateStr) {
const inputDate = new Date(dateStr)
const month = inputDate.getMonth() + 1
const day = inputDate.getDate()
const weekday = inputDate.toLocaleString('zh-CN', { weekday: 'short' })
if (isToday(dateStr)) {
return '今天'
}
return `${weekday}<br><span class="date-only">${month}/${day}</span>`
}
const todayStyle = {
fontWeight: 'bold',
backgroundColor: '#ff4d4f',
color: 'white',
padding: '4px 8px',
borderRadius: '4px'
}
</script>
<style scoped>
.interviewList {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.interviewDate {
padding: 8px;
border-radius: 4px;
transition: all 0.2s ease;
}
.interviewDate.today {
background-color: #ff4d4f;
color: white;
font-weight: bold;
}
.date-only {
font-size: 0.8em;
color: #666;
}
</style>
```
---
### ✅ 关键点说明:
| 技术点 | 说明 |
|---------------|------|
| `v-html` | 用于渲染包含 HTML 的字符串,如 `<br>`、`<span>` 等标签 |
| `{{ }}` 插值 | 会自动转义 HTML,所以 `<br>` 会被显示为文字而不是换行 |
| `formatDate()` | 返回包含 `<br>` 的字符串,用于在非“今天”时显示“周几”和“月/日”两行内容 |
---
### ✅ 示例输出(假设今天是 2025-08-30):
| 输入 key | 输出 HTML 内容 | 页面显示效果 |
|----------------|-----------------------------------------|------------------|
| `"2025-08-30"` | `"今天"` | 今天(红色背景) |
| `"2025-09-01"` | `"周一<br><span class="date-only">9/1</span>"` | 上面是“周一”,下面是“9/1”(小字体、浅色) |
---
### ✅ 安全提示:
使用 `v-html` 时需要注意:
- **不要渲染用户输入的内容**,否则可能导致 XSS 攻击
- 如果内容是用户输入的,请务必进行过滤或使用 `DOMPurify` 等库进行净化
---
###
阅读全文
相关推荐



















