【问题标题】:VueJS newline character is not rendered correctlyVueJS 换行符未正确呈现
【发布时间】:2018-08-22 05:01:37
【问题描述】:

我遇到了以下问题,我从包含换行符\n 的 API 读取数据字符串,我想在我的模板中正确显示它们。

但是当我做类似的事情时:

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

文本像普通文本一样显示为\n 字符。

响应中的文本字符串格式为"Hello, \n what's up? \n My name is Joe"

我在这里做错了什么?

【问题讨论】:

  • 您可以尝试将mytext 包装在&lt;pre&gt; 标签中或将white-space: pre; css 添加到您的&lt;p&gt; 标签中

标签: javascript string vuejs2 newline


【解决方案1】:

甚至不是 vue 问题,您可以简单地使用 CSS 并将 white-space: pre; 应用于内容。你不应该为此需要额外的包。

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>

【讨论】:

  • 请注意,如果您需要包装的文本,您可以使用white-space: pre-wrap; more details
  • white-space: pre-wrap; 帮了我大忙!请注意,white-space: break-spaces; 似乎做了非常相似的事情。其实我也分不清。
【解决方案2】:

使用&lt;pre&gt;&lt;/pre&gt; 标签pre提供pre格式化文本。更多信息MDN Pre tag docs

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>

【讨论】:

【解决方案3】:

我遇到了与vue-nl2br相同的问题

查看here

安装

npm install --save vue-nl2br

用法

import Nl2br from 'vue-nl2br'

Vue.component('nl2br', Nl2br)

查看

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

结果:

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

【讨论】:

  • 你是说 OP 必须下载、安装和使用一个包来显示新行??
  • 是的,但不只是显示其将 /n 标记转换为
  • 对于那个功能来说似乎太过分了
  • 是的,我同意:/!
  • 是的,它现在有点“过度供电”,也许我找到了更好的解决方案。如果是这样,我会在这里发布。
【解决方案4】:

这是将字符串拆分为多个&lt;div&gt; 元素的解决方案。

我也将它与 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>

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多