我试图创建一个具有动态步骤数的表单。单击按钮可以添加一个额外的步骤。在该步骤中,有几个 input
字段,但也有几个 button
用于创建更多 input
字段。
例如,有 title
和 description
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-if
和 v-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
},
如果我可以建议,您应该将每个 input
直接传递给 addVideo
或 removeVideo
(而不是 index
).我认为它使代码更简单:http://jsbin.com/pucohawuje/1/edit?html,js,output - 但我知道这可能是一个品味问题,所以我将其保留为建议。
关于javascript - 包含动态输入字段数的动态行数vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786065/