VueJS 换行符未正确渲染

问题描述 投票:0回答:5
javascript string vuejs2 newline
5个回答
66
投票

甚至不是 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>


8
投票

使用

<pre></pre>
标签来 pre 提供 pre 格式化文本。更多信息MDN 预标记文档

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>


1
投票

我面临着与我使用的相同的问题

vue-nl2br

检查这里

安装

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>

0
投票

这是将字符串拆分为多个

<div>
元素的解决方案。

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


0
投票

我有同样的问题,我使用 CSS 来解决它。

new Vue({
  el: '#app',
  data: {
    yourText: 'Lorem ipsum dolor sit amet, \n consectetur adipiscing elit, \n sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \n \n Ut enim ad minim veniam, \n quis nostrud exercitation ullamco'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<p id="app" style="white-space: break-spaces">{{yourText }}</p>

© www.soinside.com 2019 - 2024. All rights reserved.