后端返回字符串中的 \n 展示在页面上,如何处理为换行

1,011 阅读1分钟

方法一:使用v-html,有安全风险

要在 Vue 页面上将从后端返回的 \n 处理为换行,可以使用 v-html 指令和适当的 HTML 转义。具体步骤如下:

  1. 在后端返回的数据中,将 \n 替换为 <br> 标签。

    const formattedText = text.replace(/\n/g, '<br>');
    
  2. 在 Vue 组件中,使用 v-html 指令来渲染包含 <br> 标签的文本。

    <template>
      <div v-html="formattedText"></div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          rawText: 'First line\nSecond line\nThird line',
        };
      },
      computed: {
        formattedText() {
          return this.rawText.replace(/\n/g, '<br>');
        },
      },
    };
    </script>
    

使用 v-html 指令时要注意安全性,确保处理的内容没有潜在的 XSS 攻击风险。

方法二:使用 CSS 的 white-space 属性 --- 推荐使用

除了 v-html,你可以使用 CSS 来处理 \n 换行,而避免使用 HTML。具体方法如下:

通过设置 white-space: pre-line;,可以使文本中的换行符(\n)在页面上正确显示为换行。

 <template>
   <div class="formatted-text">{{ rawText }}</div>
 </template>

 <script>
 export default {
   data() {
     return {
       rawText: 'First line\nSecond line\nThird line',
     };
   },
 };
 </script>

 <style>
 .formatted-text {
   white-space: pre-line; /* 保留换行符并自动换行 */
 }
 </style>

这种方法简单安全,无需使用 v-html,适合在 Vue 中处理纯文本的换行问题。