【问题标题】:Vue how to parse a line break in a textarea string that comes from an Api?Vue如何解析来自Api的textarea字符串中的换行符?
【发布时间】:2020-11-24 11:30:27
【问题描述】:

我使用的是 Vue 2,我需要在文本区域中显示 myText 变量并带有换行符。如果我在 textarea 中使用静态变量,则换行符可以正常工作。它显示:

line one
line two2

但如果我从 API 获得 myText,它会将 \n 显示为文本:

line one\nline two2

此代码用于澄清

 <template>
  <div class="Test">  
    <textarea name="name" v-model="myText" >   </textarea> 
  </div>
</template>

JavaScript

 <script>
    export default {
      name: 'Test',
       data: () => ({
          myText: ' line one\nline two2 ' 
       }), 
       created(){
         this.getTextFromApi();
       },
       methods:{
           getTextFromApi(){ 
                ajax()
                 .done(function(Response){ 
                    this.myText = Response.text;   
                 };
           },
      }
    } 
</script>

那么如何让 textarea 读取来自 Api 的 \n 作为换行符,而不是文本?

【问题讨论】:

    标签: javascript vue.js vuejs2 textarea line-breaks


    【解决方案1】:

    您的 API 文本似乎有双反斜杠,例如“\n”之类的字符串被转义到“\\n”并输入到您的 API 中。如果是这样,这将起作用:

    this.myText = Response.text.replace('\\n','\n');
    

    这会在\n 中留下换行符。回调似乎也需要一个箭头函数:

    .done((Response) => { 
       this.myText = Response.text.replace('\\n','\n');   
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2019-11-08
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      相关资源
      最近更新 更多