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>
- 設置元素的 
white-space為pre-line可解析
\n並自動換行。<style> .multiline { white-space: pre-line; } </style> - 替換
\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>

Comments