在 VueJS 中呈现换行符

我正在创建一个笔记应用程序,用户可以通过在文本区域中输入多行文本来添加笔记。当我在 Firebase 中保存笔记时,它被保存为新行(n)字符,我希望将其可视化。

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

132145 次浏览

将内容包装在 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!

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

在实际描述了我的问题后,我得到了使用前标签的想法,这是为预先格式化的文本。此标记将尊重’t n’字符,并正确地从框中呈现文本! 虽然这些句子不会自动被打断,不会溢出宽度。 通过一些 CSS,我可以得到与其他元素相同的行为。

Html:

\{\{note.content}}

css:

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

就像@shelvacu 说的 Html 标记保留空白

然而,使用它有一个严重的缺点: 标签本身继承了大量不必要的样式,这些样式来自于在项目中使用的 CSS 框架(例如 Bootstrap)。

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

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

行为与 <pre>标签完全相同。

请注意,white-space: pre仍然保持文本的“原样”-如果你想在必要时使用额外的换行符: white-space: pre-wrap

See: w3schools.com CSS white-space Property

I'm able to make it work with backticks (`)

<pre>\{\{textRenderedAsItIs}}</pre>

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

Use white-space: pre-line; CSS property.

Mozzila Doc中写入 pre-line值:

空白序列被折叠。换行处断行 characters, at <br>, and as necessary to fill line boxes.

转换成

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

Hope this would add value to new visitors.

用户输入。

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

我不是 pre的粉丝(除了在调试方面!)所以这里有另一种方法来处理这个使用 v-for。这使得调整格式变得更加容易(例如,您可能希望使用一个列表或其他不是 spanbr的东西)

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

你可以使用 v-html

<span v-html="yourContent"></span>

 

data():{
return{
yourContent: "Line 1 <br> Line 2"
}
}