html
<div class="dialog-content">
<span>{{ previewContent }}</span>
</div>
js
const previewContent = ref("Authorization: Bearer 【eyJhbGci...】<br\>X-Access-Token: 【eyJhbGci...】");
- 在前端 Vue3 开发中,字符串中的
<br\>标签被直接当作文本显示出来了,而不是被解析为 HTML 换行标签
处理策略
- 最直接的方式是使用
v-html指令,但是使用v-html指令时要确保内容是可信任的,避免 XSS 攻击
html
<div class="dialog-content">
<span v-html="previewContent"></span>
</div>
- 更安全、更推荐的方式是,避免使用
v-html指令,可以用 CSS 的white-space属性来处理换行
html
<div class="dialog-content multiline-text">
<span>{{ previewContent }}</span>
</div>
js
const previewContent = ref("Authorization: Bearer 【eyJhbGci...】\nX-Access-Token: 【eyJhbGci...】");
- 最灵活的方式是,使用数组渲染,可以对每一行进行单独控制
html
<div class="dialog-content">
<div v-for="(line, index) in previewContents" :key="index">
{{ line }}
</div>
</div>
js
const previewContents = ref(["Authorization: Bearer 【eyJhbGci...】", "X-Access-Token: 【eyJhbGci...】"]);