前端处理--接口返回的数据换行方法

439 阅读2分钟

这篇笔记📒主要记录,前端处理--接口返回的数据换行方法: 后台接口返回的数据,有的内容字段换行标识用的是<br>, 有的是\n,有2种需求,

  1. 第一种表单里文本框字段换行, 通过textarea的\n形式
  2. 第二种是普通换行,通过v-html解析<br>的形式
表单里文本框换行

在表单展示,输入框类型为textarea的时候(既然要换行,就用textarea),如果是\n能够自动换行。 截图证明类型为textarea,\n能够自动处理换行

image.png

我们知道了textarea能够处理\n换行,那就把返回的数据对象,里面的字段如果有<br>,就把<br>都改成\n,

const obj = {
  key1: "Hello<br>World",
  key2: "No line break here",
  key3: "Another<br>example",
  key4: "Just plain text",
  key5: "Some text",
  key6: "More text<br>"
};

// Iterate over the key-value pairs in the object
Object.entries(obj).forEach(([key, value]) => {
  // Check if the value is a string and contains <br>
  if (typeof value === 'string' && value.includes('<br>')) {
    // Replace all occurrences of <br> with \n
    obj[key] = value.replace(/<br>/g, '\n');
  }
});

console.log(obj);

通过Object.entries, 把对象的每对key, value组成一个数组,如果value是字符串,并且包含<br>, 就把<br>改成\n就可以了

普通的换行

普通的换行,需要利用v-html指令,因为v-html能够解析html标签,<br>是换行标签,所以可以把返回的数据,如果包含\n都转成<br>

    const obj = {
      key1: "Hello<br>World",
      key2: "No line break here",
      key3: "Another<br>example",
      key4: "Just plain text",
      key5: "Some text",
      key6: "More text<br>"
    };

    // Iterate over the key-value pairs in the object
    Object.entries(obj).forEach(([key, value]) => {
      // Check if the value is a string and contains <br>
      if (typeof value === 'string' && value.includes('\n')) {
        // Replace all occurrences of <br> with \n
        obj[key] = value.replace(/\n/g, '<br>');
      }
    });

    console.log(obj);

如果不转换数据,在template用到的时候转,也可以

<template>
  <div v-html="{ formatLineBreaks(form.check_items )}"></div>
<template>
<script setup>
const formatLineBreaks = (inputString) => {
   if (typeof inputString === 'string') {
     return inputString.includes('\n') ? inputString.replace(/\n/g, '<br>') : inputString
   } else {
     return ''
   }
}
</script>

demo演示

<template>
 <el-input
   v-model="textarea1"
   style="width: 240px"
   maxlength="40"
   placeholder="Please input"
   show-word-limit
   type="textarea"
   :rows="3"
 />
 <div style="margin: 20px 0" />
 <el-input
   v-model="textarea2"
   maxlength="40"
   style="width: 240px"
   placeholder="Please input"
   show-word-limit
   type="textarea"
   :rows="4"
 />
 <div v-html="str" style="margin-bottom: 40px; margin-top: 20px;"></div>

 <div v-html="str1"></div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
const textarea1 = ref('外面乌云密布<br>还有几分钟就下班了<br>20240828')
const textarea2 = ref('外面乌云密布\n还有几分钟就下班了\n20240828')
const str = `已经6点半了<br> 外面在下雨`
const str1 = `已经6点半了\n 外面在下雨`
</script>

image.png