在VueJS中渲染换行符

时间:2016-04-19 21:16:41

标签: javascript vue.js

我正在创建一个笔记应用,用户可以通过在textarea中输入多行文字来添加笔记。当我在Firebase中保存笔记时,它将使用我想要显示的换行符(\ n)保存。

因此,我写了一个过滤器,用<br />取代这些字符,效果很好 但是,现在我需要使用{{{note.content}}}来渲染我的数据,并且用户可以注入将要执行的HTML,CSS和JS。 我应该使用类似DOMPurify的内容来验证内容,还是有办法安全地呈现换行符?

8 个答案:

答案 0 :(得分:86)

正如@shelvacu所说, <pre> html标签会保留空格

但是使用它有一个严重的缺点:标签本身从项目中使用的CSS框架(例如Bootstrap)继承了大量不必要的样式。

要保留空格并避免继承任何不必要的样式,请使用:

<span style="white-space: pre;">Some whitespaced content</span>

会像<pre>标签那样行事。

请注意,white-space: pre仍为“文字”,如果您希望在必要时使用其他换行符:white-space: pre-wrap

请参阅:w3schools.com CSS white-space Property

答案 1 :(得分:28)

将内容包装在pre元素中。

<pre>元素会在其中提供空白,例如:

This is followed by a newline,
not that you can tell
<br />
<br />
<pre>You can see the newline after me!
Woohoo!</pre>

将导致:

This is followed by a newline, not that you can tell

You can see the newline after me!
Woohoo!

这样,您就不需要对换行进行任何过滤。

答案 2 :(得分:22)

在实际描述我的问题后,我明白了使用预格式文本的预标签。此标记将尊重&#39; \ t \ n&#39;字符并正确地呈现文本! 虽然句子不会自动破坏并溢出宽度。 通过一些CSS,我能够获得与其他元素相同的行为。

HTML:     

{{note.content}}

的CSS:

.note pre {
  white-space: pre-wrap; 
  word-wrap: break-word;
  font-family: inherit;
}

答案 3 :(得分:7)

希望这能为新访问者增加价值。

来自用户的输入。

I am big line with lots and lots of text which would make me not fit.

Line two ✌ 
Line three

Input from user

输出的最佳方法

<span style="white-space: pre-line">Your Content</span>

Best Approach Output

其他方法的问题

<span style="white-space: pre">Your Content</span>

将导致在 y 轴上增加一个滚动 with pre style

参考及更多详情:https://css-tricks.com/almanac/properties/w/whitespace

答案 4 :(得分:3)

使用white-space: pre-line; CSS属性。

pre-line的值在Mozzila Doc中写入:

  

空白序列被折叠。行在换行符处断开   字符,<br>,并根据需要填充行框。

答案 5 :(得分:3)

我不是 pre 的忠实粉丝(除了调试!)所以这里是另一种使用 v-for 处理这个问题的方法。这样可以更轻松地调整格式(例如,您可能想使用列表或其他不是 spanbr 的内容)

<span
   v-for="(line,lineNumber) of stringWithNewlines.split('\n')" 
   v-bind:key="lineNumber" >
  {{ line }}<br/>
</span>

答案 6 :(得分:1)

我能够使用反引号(`)

<pre>{{textRenderedAsItIs}}<pre>

data():{
  return{
    textRenderedAsItIs:`Hello
                        World`
   }
}

答案 7 :(得分:1)

将\ n转换为

if (this.content.my_val && this.content.my_val !== '') {
    return this.content.my_val.replace(/\n/g, '<br />')
}