使用 v-for 指令和数组来实现在 Uni-app 中动态增减表单项并渲染多个数据

时间:2025-02-13 06:57:18
  1. 在 data 中定义一个数组,用于存储表单项的数据:

 
data() {
  return {
    formItems: []
  }
}
  1. 在模板中使用 v-for 指令渲染表单项:
<template>
  <div>
    <div v-for="(item, index) in formItems" :key="index">
      <input type="text" v-model="">
      <button @click="removeFormItem(index)">删除</button>
    </div>
    <button @click="addFormItem">添加表单项</button>
  </div>
</template>

  1. 在 methods 中定义添加和删除表单项的方法:
methods: {
  addFormItem() {
    ({ value: '' });
  },
  removeFormItem(index) {
    (index, 1);
  }
}

这样,每点击一次 “添加表单项” 按钮,就会新增一个表单项,并且你可以通过输入框的 v-model 来动态修改表单项的值。点击对应的 “删除” 按钮可以移除对应的表单项。