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

Vue3实现下拉框与输入框联动生成表格内动态文本框需求

Vue3 动态生成表格文本框实现方案

核心实现逻辑

  • 用响应式变量管理下拉选择值、输入内容及表格动态条目
  • 仅当选中Option 1且输入内容非空时,允许添加新文本框到表格
  • 表格内文本框支持双向绑定,可实时编辑内容

完整代码示例

<template>
  <div class="container">
    <!-- 选择与输入区域 -->
    <div class="input-group">
      <select v-model="selectedOption">
        <option value="">请选择选项</option>
        <option value="Option 1">Option 1</option>
        <option value="Option 2">Option 2</option>
      </select>
      <input 
        type="text" 
        v-model="inputValue" 
        placeholder="输入内容(如Grass、Table)"
        @keyup.enter="addTextBox"
      />
      <button @click="addTextBox" :disabled="!canAdd">添加文本框</button>
    </div>

    <!-- 动态表格 -->
    <table class="dynamic-table" v-if="tableRows.length > 0">
      <thead>
        <tr>
          <th>序号</th>
          <th>内容</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, index) in tableRows" :key="row.id">
          <td>{{ index + 1 }}</td>
          <td><input type="text" v-model="row.content" /></td>
          <td><button @click="removeRow(index)">删除</button></td>
        </tr>
      </tbody>
    </table>
    <p v-else>暂无动态文本框,请添加</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 响应式变量定义
const selectedOption = ref('')
const inputValue = ref('')
const tableRows = ref([])
let idCounter = 1

// 判断是否满足添加条件
const canAdd = computed(() => {
  return selectedOption.value === 'Option 1' && inputValue.value.trim() !== ''
})

// 添加文本框到表格
const addTextBox = () => {
  if (!canAdd.value) return
  tableRows.value.push({
    id: idCounter++,
    content: inputValue.value.trim()
  })
  inputValue.value = '' // 清空输入框
}

// 删除指定行
const removeRow = (index) => {
  tableRows.value.splice(index, 1)
}
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}
.input-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
.input-group select, .input-group input {
  padding: 8px;
  font-size: 14px;
}
.input-group button {
  padding: 8px 16px;
  cursor: pointer;
}
.dynamic-table {
  width: 100%;
  border-collapse: collapse;
}
.dynamic-table th, .dynamic-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: left;
}
.dynamic-table th {
  background-color: #f5f5f5;
}
</style>

关键细节说明

  • 通过v-model实现下拉框、输入框与响应式变量的双向绑定
  • 用computed属性做条件校验,避免无效添加操作
  • 支持点击按钮或按下回车键两种添加触发方式,添加后自动清空输入框
  • 表格行使用唯一id作为key,避免Vue渲染警告
  • 提供删除行功能,动态更新表格内容

内容的提问来源于stack exchange,提问作者Shehab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:16:14