vue3 - json檔案的字串處理

在json文件中偶爾會遇到字串內建換行符號,例如\n,這時候有幾種方式可以在模板中直接讓顯示的文字跟著換行

//json
{
  "message": "Hello,\nthis is my first post!\nPlease follow"
}
<template>
  <div>
    <p class="multiline">{{ jsonData.message }}</p>
  </div>
</template>

<script setup>
import jsonData from "../" 

</script>


 

  1. 設置元素的 white-spacepre-line

    可解析 \n 並自動換行。

    <style>
    .multiline {
      white-space: pre-line; 
    }
    </style>
  2. 替換\n<br> 標籤

這個方式要用 v-html

<template>
  <div>
    <p v-html="formattedMessage"></p>
  </div>
</template>

<script setup>
import jsonData from "../" 
const formattedMessage = computed(() => {
    return jsonData.message.replace(/\n/g, '<br>');
})
</script>

 

pre-line的用法

 

Related post

J J
JAVASCRIPT

使用vue3 自動判定日期

情境:我的專案有活動紀錄,格式為json,本來的網頁非常的土法煉鋼,還沒到來的活動日期就在上方,過期的活動在下方。有一天我突然懶惰了(?)希望可以自動抓取今天日期判斷是否過期 使用框架:vue 3…

Comments