Tobias Schäfer
Tobias Schäfer

Reputation: 1358

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.

But when I do something like:

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

The text is display with \n characters in it like normal text.

The text string from the response is in the format of "Hello, \n what's up? \n My name is Joe".

What am I doing wrong here?

Upvotes: 26

Views: 37351

Answers (5)

Olivieris
Olivieris

Reputation: 11

I had the same issue and I used CSS to resolve it.

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>

Upvotes: 1

Migio B
Migio B

Reputation: 417

This is a solution to split string in multiple <div> elements.

I use this also with i18n plugin and I like it because I don't need to touch 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>

Upvotes: 1

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Not even a vue issue you could simply use CSS and apply 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>

Upvotes: 71

DobleL
DobleL

Reputation: 3918

Use the <pre></pre> tag to preserve the preformated text. More info 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>

Upvotes: 9

I was facing same issus i was using 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>

Upvotes: 1

Related Questions