css的white-space: pre
用户从别的地方复制的配置文件,粘贴到输入框内,需要保留原始格式发送给后端。
核心步骤:
### 1. 格式保持机制
- white-space: pre :这是最关键的CSS属性,确保所有空格、制表符、换行符都被保留
- wrap="off" :防止浏览器自动换行,保持原始的行结构
- 等宽字体 :使用Consolas等编程字体,确保字符对齐和格式清晰
### 2. 数据绑定
- 使用Vue3的 v-model="inputJson" 实现双向数据绑定
- 用户粘贴的内容会完整存储在 inputJson.value 中,包括所有格式字符
### 3. 用户体验
- 大尺寸textarea(400px高度)提供充足的编辑空间
- 关闭拼写检查避免干扰
- 聚焦时的视觉反馈
简单来说,这个组件的核心就是让用户能够粘贴任何文本内容(特别是配置文件、JSON等),并且保证粘贴的内容格式完全不变,然后可以原样发送给后端处理。
下面是一个小demo
<template><div class="json-input-container"><textarea v-model="inputJson" placeholder="请粘贴配置文件内容,将保持原始格式"class="json-textarea"rows="15"wrap="off"spellcheck="false"></textarea><div class="format-info"><small>保持原始格式,包括换行符、空格和缩进,内容将原样发送给后端</small></div></div>
</template><script setup>
import {ref,watch} from "vue";// 输入内容,保持原始格式
let inputJson = ref('');
watch(inputJson, (newValue) => {console.log(JSON.stringify(newValue));
})
</script><style scoped>
.json-input-container {width: 100%;max-width: 800px;margin: 0 auto;
}.json-textarea {width: 100%;min-height: 400px;padding: 16px;border: 2px solid #e1e5e9;border-radius: 8px;font-family: 'Consolas', 'Monaco', 'Courier New', monospace;font-size: 14px;line-height: 1.5;background-color: #f8f9fa;color: #333;resize: vertical;outline: none;transition: border-color 0.3s ease;white-space: pre;overflow-wrap: normal;overflow-x: auto;box-sizing: border-box;
}.json-textarea:focus {border-color: #007bff;background-color: #fff;box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}.json-textarea::placeholder {color: #6c757d;font-style: italic;
}.format-info {margin-top: 8px;text-align: center;color: #6c757d;
}.format-info small {font-size: 12px;
}
</style>