Vue.js获取textarea每行内容方案求助(Composition/Options API)
解决Vue中获取textarea每行内容的方案
Options API 实现
模板代码
<template> <div> <textarea v-model="textareaValue" @input="handleLineSplit" rows="5" placeholder="输入内容,按换行分割" ></textarea> <div class="line-list"> <p v-for="(line, index) in lines" :key="index" class="line-item"> 第{{ index + 1 }}行:{{ line }} </p> </div> </div> </template>
脚本代码
<script> export default { data() { return { textareaValue: '', lines: [] } }, methods: { handleLineSplit() { // 兼容Windows(\r\n)和Linux(\n)换行格式 this.lines = this.textareaValue.split(/\r?\n/) } } } </script>
Composition API 实现
模板代码
<template> <div> <textarea v-model="textareaValue" rows="5" placeholder="输入内容,按换行分割" ></textarea> <div class="line-list"> <p v-for="(line, index) in lines" :key="index" class="line-item"> 第{{ index + 1 }}行:{{ line }} </p> </div> </div> </template>
脚本代码
<script setup> import { ref, computed } from 'vue' const textareaValue = ref('') // 实时监听内容变化,自动分割每行 const lines = computed(() => { return textareaValue.value.split(/\r?\n/) }) </script>
补充说明
- 两种方案都兼容不同系统的换行格式
- 如果需要过滤空行,可在分割后追加
.filter(line => line.trim() !== '') - 渲染结构可根据需求调整,比如用列表、卡片替换
<p>标签
内容的提问来源于stack exchange,提问作者kadirklc
相关产品推荐
相关产品推荐

