VueJS newline character is not rendered correctly

前端 未结 3 1488
心在旅途
心在旅途 2021-02-19 00:39

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

相关标签:
3条回答
  • 2021-02-19 00:47

    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>

    0 讨论(0)
  • 2021-02-19 00:49

    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>
    
    0 讨论(0)
  • 2021-02-19 00:50

    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>

    0 讨论(0)
提交回复
热议问题