Vue.js中字符串使用\n无法实现换行,如何正确渲染换行效果?
Vue 字符串换行渲染解决方案
默认HTML会合并所有连续空白字符(包括\n、空格、制表符),所以直接在字符串里插入\n不会在页面显示换行效果,可选择以下3种方案实现需求:
方案1:使用white-space CSS属性(最推荐)
- 字符串内正常用
\n分隔内容,不需要修改原字符串结构 - 给渲染字符串的标签添加
white-space: pre-line样式,即可自动识别\n实现换行,无安全风险 - 示例代码:
<template> <!-- 渲染带\n的字符串 --> <div class="text-wrap">{{ content }}</div> </template> <script setup> import { ref } from 'vue' // 直接用\n换行赋值 const content = ref('String 1\nString 2\nString 3') </script> <style scoped> .text-wrap { /* 核心样式,识别\n自动换行,同时合并多余空格 */ white-space: pre-line; } </style>
方案2:替换换行符为<br>配合v-html渲染
- 仅适用于内容为可信任场景,用户输入内容使用此方案有XSS注入风险
- 先将字符串内的
\n全局替换为<br>标签,再用v-html指令渲染 - 示例代码:
<template> <div v-html="formattedContent"></div> </template> <script setup> import { ref, computed } from 'vue' const rawContent = ref('String 1\nString 2\nString 3') // 把所有\n替换为<br>标签 const formattedContent = computed(() => rawContent.value.replace(/\n/g, '<br>')) </script>
方案3:拆分字符串为数组循环渲染
- 无安全风险,适合需要给每行内容单独添加样式的场景
- 用
split('\n')将字符串按换行符拆分为数组,再用v-for循环逐行渲染 - 示例代码:
<template> <div> <div v-for="(line, idx) in contentLines" :key="idx"> {{ line }} </div> </div> </template> <script setup> import { ref, computed } from 'vue' const rawContent = ref('String 1\nString 2\nString 3') // 按换行符拆分字符串为数组 const contentLines = computed(() => rawContent.value.split('\n')) </script>
内容的提问来源于stack exchange,提问作者Vineet
相关产品推荐
相关产品推荐

