vue实现换行
在 Vue 中实现换行的方法
使用 \n 和 CSS 的 white-space 属性
在 Vue 模板或数据绑定中,可以使用 \n 表示换行符,并通过 CSS 的 white-space: pre-line 或 white-space: pre-wrap 使其生效。

<template>
<div class="text-with-newline">{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: '第一行\n第二行\n第三行'
}
}
}
</script>
<style>
.text-with-newline {
white-space: pre-line;
}
</style>
使用 <br> 标签
在需要换行的地方直接插入 <br> 标签,适用于静态内容或动态生成的 HTML。

<template>
<div v-html="htmlMessage"></div>
</template>
<script>
export default {
data() {
return {
htmlMessage: '第一行<br>第二行<br>第三行'
}
}
}
</script>
使用 v-for 和数组
将内容拆分为数组,通过 v-for 循环渲染,并在每项后添加换行。
<template>
<div>
<span v-for="(line, index) in lines" :key="index">
{{ line }}<br>
</span>
</div>
</template>
<script>
export default {
data() {
return {
lines: ['第一行', '第二行', '第三行']
}
}
}
</script>
使用计算属性处理换行
通过计算属性动态处理文本中的换行符,返回带有 <br> 的 HTML 字符串。
<template>
<div v-html="formattedMessage"></div>
</template>
<script>
export default {
data() {
return {
rawMessage: '第一行\n第二行\n第三行'
}
},
computed: {
formattedMessage() {
return this.rawMessage.replace(/\n/g, '<br>')
}
}
}
</script>
注意事项
- 使用
v-html时需注意 XSS 攻击风险,确保内容可信。 white-space: pre-line会合并连续空格,但保留换行符;pre-wrap会保留所有空格和换行符。- 动态生成的内容推荐使用计算属性或方法处理,以提高可维护性。






