vue实现换行
Vue 中实现换行的几种方法
在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法:
使用 HTML 的 <br> 标签
在模板中直接使用 <br> 标签可以实现换行效果:

<template>
<div>
第一行<br>
第二行
</div>
</template>
使用 CSS 的 white-space 属性
通过 CSS 设置 white-space: pre-line 或 white-space: pre-wrap 可以保留文本中的换行符:
<template>
<div style="white-space: pre-line;">
第一行
第二行
</div>
</template>
使用 v-html 指令
如果文本内容中包含 HTML 标签(如 <br>),可以使用 v-html 指令渲染:

<template>
<div v-html="textWithBreaks"></div>
</template>
<script>
export default {
data() {
return {
textWithBreaks: '第一行<br>第二行'
}
}
}
</script>
使用 JavaScript 的 split 和 join 方法
将文本按换行符分割后渲染为多个段落或 <br> 标签:
<template>
<div>
<p v-for="(line, index) in lines" :key="index">{{ line }}</p>
</div>
</template>
<script>
export default {
data() {
return {
text: '第一行\n第二行'
}
},
computed: {
lines() {
return this.text.split('\n')
}
}
}
</script>
使用模板字符串
在模板字符串中直接插入换行符:
<template>
<div>
{{ multilineText }}
</div>
</template>
<script>
export default {
data() {
return {
multilineText: `第一行
第二行`
}
}
}
</script>
注意事项
- 使用
v-html时需注意 XSS 安全问题,确保内容可信。 - CSS 的
white-space方法适用于保留原始文本格式。 - 对于动态内容,推荐使用
split和v-for的方式,灵活性更高。






