The processing of line breaks in vue that does not wrap and does not take effect (\n or <br>)

Introduction: I stumbled upon the newline character in vue\n,<br>do not wrap and do not take effect

First look at a piece of code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
       	   <span>{
   
   {msg}}</span>
        </div>
    </body>
    <script src="../vue.js"></script>
    <script>
       var vm = new Vue({
            el: '#app',
            data: {
              msg:'这是一个消息\n这是另外一个消息',
            }
        })
    </script>
</html>

Page effect:

It doesn’t have the line-breaking effect we want, and the \n in msg doesn’t work either

Solution (style="white-space: pre-wrap;")

<span style="white-space: pre-wrap;">{
   
   {msg}}</span>

You can wrap at this time

If it is br, what will be the effect?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
       	   <span style="white-space: pre-wrap;">{
   
   {msg}}</span>
        </div>
    </body>
    <script src="../vue.js"></script>
    <script>
       var vm = new Vue({
            el: '#app',
            data: {
              msg:'这是一个消息<br>这是另外一个消息',
            }
        })
    </script>
</html>

Page effect:

<br>It was rendered directly on the page as a character, and it failed to achieve the effect of line wrapping.

Solution:

1. Use v-html to process

(Because <br> is used, this sentence style="white-space: pre-wrap;" can be omitted)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
       	   <span v-html='msg'></span>
        </div>
    </body>
    <script src="../vue.js"></script>
    <script>
       var vm = new Vue({
            el: '#app',
            data: {
              msg:'这是一个消息<br>这是另外一个消息',
            }
        })
    </script>
</html>

2. Use filter to process, replace <br> with \n

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
       	   <span style="white-space: pre-wrap;">{
   
   {msg | lineBreak}}</span>
        </div>
    </body>
    <script src="../vue.js"></script>
    <script>
       var vm = new Vue({
            el: '#app',
            data: {
              msg:'这是一个消息<br>这是另外一个消息',
            },
            filters:{
            	lineBreak:function(data){
            		return data.replace(/<br>/g,'\n');
            	}
            }
        })
    </script>
</html>

 

Guess you like

Origin blog.csdn.net/dkm123456/article/details/114644775