javascript - 包含动态输入字段数的动态行数vue

标签 javascript vue.js vuejs2

我试图创建一个具有动态步骤数的表单。单击按钮可以添加一个额外的步骤。在该步骤中,有几个 input 字段,但也有几个 button 用于创建更多 input 字段。

例如,有 titledescription input,还有 Add a Video 的链接将创建另一个 input 字段并将该链接更改为 Remove the Video

所有这些步骤都必须创建一个对象数组,其中每个对象可能包含略有不同的属性。我是 vue 的新手,它非常令人困惑。

<div v-for="(row, index) in rows" :key="index">

<input type="text" v-model="row.title">
<input type="text" v-model="row.description">
<div v-show="row.video">
    <input type="text" v-model="row.video">
</div>
    <a v-on:click="addVideo(index);" style="cursor: pointer">Add Video element</a><br>

<a v-on:click="removeElement(index);" style="cursor: pointer">Remove</a>
</div>
<div>
    <button class="button btn-primary" @click="addRow">Add Step</button>
</div>

和我的职能:

addRow () {
  this.rows.push({
    title: '',
    description: '',
    file: {
      name: 'Choose File'
    }
  })
},
addVideo (index) {
  this.rows[index].video = ' '
  this.$forceUpdate()
},
removeElement (index) {
  this.rows.splice(index, 1)
}

或此链接中的代码:http://jsbin.com/punekukayu/1/edit?html,js,output

此时我不知道如何从该步骤中删除 Add Video element 链接,我想这是这里不好的做法。

最佳答案

您可以使用 v-ifv-else:

<a v-if="input.video === null" v-on:click="addVideo(index);" style="cursor: pointer">Add Video element</a>
<template v-else>
    <input type="text" v-model="input.video">
    <a v-on:click="removeVideo(index);" style="cursor: pointer">Remove Video element</a>
</template>

默认情况下,您会将 video 添加为 null,因此您无需调用 $forceUpdate:

addRow() {
  this.inputs.push({
    one: '',
    two: '',
    video: null                     // added
  })
},
addVideo (index) {
  this.inputs[index].video = '';    // changed
},
removeVideo (index) {
  this.inputs[index].video = null;  // added
},

Updated JSBin here .


如果我可以建议,您应该将每个 input 直接传递给 addVideoremoveVideo(而不是 index ).我认为它使代码更简单:http://jsbin.com/pucohawuje/1/edit?html,js,output - 但我知道这可能是一个品味问题,所以我将其保留为建议。

关于javascript - 包含动态输入字段数的动态行数vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786065/

相关文章:

javascript - 在 html5 日期字段上启用复制/粘贴

javascript - 选中复选框时删除当前行 (tr)

javascript - 忽略@RenderBody()

vue.js - @vue/cli-plugin-pwa 没有创建 service-worker.js

http - 如何在 vue-cli 中设置 HTTP header ?

javascript - VueJS 在渲染函数调用中将 props 传递给子级

javascript - ExtJS X模板 : calling a template from another template

javascript - 如何合并属性 JavaScript 对象

vue.js - 尝试使用 vee-validate 时验证不存在的字段错误

laravel - 带有 vue 2 组件的 vue 路由器不适用于 laravel 5.8