[Vuejs]-How to preserve \n on front-end when fetching data from firebase database?

1👍

You could replace the \n with <br/> and display your it as html.

let str = "some data. more data.\nsomething";

str = str.replace('\n', '<br/>');
// "some data. more data.<br/>something"

And then display it using the v-html directive.

<span v-html="str"></span>

This will display your content as html.

However : dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS vulnerabilities. Only use HTML interpolation on trusted content and never on user-provided content.

See here :
https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML

Example :

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    answers: ["some data", "some data. more data.\nsomething"]
  },
  computed: {
    transformed_answers() {
      return this.answers.map(a => a.replace('\n', '<br/>'));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="answer in transformed_answers">
    <p v-html="answer"></p>
  </div>
</div>

Leave a comment