You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:45:48