How to fix newline character is not rendered correctly with Vue.js and JavaScript?

Sometimes, we want to fix newline character is not rendered correctly with Vue.js and JavaScript.

In this article, we’ll look at how to fix newline character is not rendered correctly with Vue.js and JavaScript.

How to fix newline character is not rendered correctly with Vue.js and JavaScript?

To fix newline character is not rendered correctly with Vue.js and JavaScript, we can set the white-space CSS property to pre.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and the app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <div style="white-space: pre;">{{ text }}</div>
  `,
  data: {
    text: 'Hello Vue.nThis is a line of text.nAnother line of text.n'
  },
})

We render the newline characters in text by setting the white-space CSS property to pre.

Therefore, we get:

Hello Vue.
This is a line of text.
Another line of text.

displayed.

Conclusion

To fix newline character is not rendered correctly with Vue.js and JavaScript, we can set the white-space CSS property to pre.