简体   繁体   English

VueJS 换行符未正确呈现

[英]VueJS newline character is not rendered correctly

I got the following problem, I read data string from an API which contains new line characters \\n and I want to display them correctly in my template.我遇到了以下问题,我从包含换行符\\n的 API 读取数据字符串,我想在我的模板中正确显示它们。

But when I do something like:但是当我做类似的事情时:

<p>{{ mytext }}</p>

The text is display with \\n characters in it like normal text.文本像普通文本一样显示为\\n字符。

The text string from the response is in the format of "Hello, \\n what's up? \\n My name is Joe" .响应中的文本字符串的格式为"Hello, \\n what's up? \\n My name is Joe"

What am I doing wrong here?我在这里做错了什么?

Not even a vue issue you could simply use CSS and apply white-space: pre;甚至不是 vue 问题,您可以简单地使用 CSS 并应用white-space: pre; to the content.到内容。 You shouldn't need an additional package for this.您不应该为此需要额外的包。

 new Vue({ el: '#app', data: { text: 'Hello Vue.\\nThis is a line of text.\\nAnother line of text.\\n' } })
 .pre-formatted { white-space: pre; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script> <div id="app"> <div class="pre-formatted">{{ text }}</div> </div>

Use the <pre></pre> tag to pre serve the pre formated text.使用<pre></pre>标签预先服务于格式化文本。 More info MDN Pre tag docs更多信息MDN Pre 标签文档

 new Vue({ el: '#app', data: { text: 'Hello, \\n what\\'s up? \\n My name is Joe' } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script> <div id="app"> <pre>{{ text }}</pre> </div>

I was facing same issus i was using vue-nl2br我面临同样的问题,我正在使用vue-nl2br

check it here在这里检查

Install安装

npm install --save vue-nl2br

Usage用法

import Nl2br from 'vue-nl2br'

Vue.component('nl2br', Nl2br)

View查看

<nl2br tag="p" :text="`myLine1\nmyLine2`" />

result :结果:

<p>myLine1<br>myLine2</p>

This is a solution to split string in multiple <div> elements.这是在多个<div>元素中拆分字符串的解决方案。

I use this also with i18n plugin and I like it because I don't need to touch CSS.我也将它与 i18n 插件一起使用,我喜欢它,因为我不需要接触 CSS。

 new Vue({ el: '#app', data: { text: ['Hello Vue.','This is a line of text.','Another line of text.',''] } })
 .pre-formatted { white-space: pre; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script> <div id="app"> <div v-for="text of text">{{ text }}</div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM