vue替换实现换行
在 Vue 中实现文本换行的几种方法
使用 v-html 指令
将包含换行符(如 \n)的字符串转换为 <br> 标签后渲染。需确保内容安全,避免 XSS 风险。

<template>
<div v-html="formattedText"></div>
</template>
<script>
export default {
data() {
return {
text: '第一行\n第二行'
};
},
computed: {
formattedText() {
return this.text.replace(/\n/g, '<br>');
}
}
};
</script>
使用 CSS 的 white-space 属性
通过 CSS 保留原始文本的换行符和空格,适合显示预格式化文本。

.pre-formatted {
white-space: pre-line;
}
<template>
<div class="pre-formatted">{{ text }}</div>
</template>
使用 <pre> 标签
保留所有空格和换行符,适合代码或固定格式文本展示。
<template>
<pre>{{ text }}</pre>
</template>
组合计算属性和模板
通过计算属性拆分文本为数组,在模板中循环渲染并添加 <br>。
<template>
<div>
<span v-for="(line, index) in lines" :key="index">
{{ line }}<br v-if="index !== lines.length - 1" />
</span>
</div>
</template>
<script>
export default {
computed: {
lines() {
return this.text.split('\n');
}
}
};
</script>
注意事项
- 使用
v-html时需对动态内容进行转义,防止恶意脚本注入。 - CSS 方案(如
white-space: pre-line)更轻量且性能友好,推荐优先考虑。 - 若需支持复杂换行逻辑(如 Markdown),可引入第三方库如
marked或自定义解析器。






