我按照此处创建动态表单元素的解决方案: Dynamically adding different components in Vue
效果很好,我的下一个难题是,如果用户添加太多表单元素,我想删除表单元素。
它的工作方式是用户创建一个“集合”,该集合被定义为一组输入。因此,每组可能适合不同的人或地点等。
这是我的 JSfiddle https://jsfiddle.net/61x784uv/
HTML
<div id="component-pii-input" v-for="field in fields" v-bind:is="field.type" :key="field.id">
</div>
<button id='button-add-pii-component' v-on:click="addFormElement('pii-entry-field')">Add Set</button>
</div>
Javascript
Vue.component('pii-entry-field', {
data: function () {
return {
fields: [],
count: 0,
}
},
methods: {
addFormElement: function(type) {
this.fields.push({
'type': type,
id: this.count++
});
},
},
template: ` <div class='pii-field'><div>
<component v-for="field in fields" v-bind:is="field.type":key="field.id"></component>
</div>
<button id='button-add-pii-input' v-on:click="addFormElement('pii-input-field')">Add Input</button>
<hr>
</div>`,
})
Vue.component('pii-input-field', {
data: function () {
return {
}
},
template: ` <div>
<select>
<option disabled>Select Classification</option>
<option>Name</option>
<option>Address</option>
<option>Email</option>
<option>Phone</option>
<option>Medical</option>
<option>Financial</option>
</select>
<div>
<input type="text" placeholder="Input">
</div>
<button v-on:click="removeFormElement">Remove Input</button></span>
</div>`,
})
var app = new Vue({
el: '#app',
data: {
fields: [],
count: 0,
},
methods: {
addFormElement: function(type) {
this.fields.push({
'type': type,
id: this.count++
});
},
}
});
最佳答案
这是一个工作 fiddle :https://jsfiddle.net/e12hbLcr/
演练:
您需要为组件提供某种 id 才能知道应删除哪个组件。您可以使用 Prop 来做到这一点。
<组件 v-for="字段中的字段"v-bind:is="field.type":id="field.id":key="field.id">
现在在子组件中创建函数并编辑按钮,以便它发送 id。
请记住,在 Vue 中,props 向下(父 -> 子)而事件向上(子-父)。所以现在我们需要告诉父级这个按钮被点击并且ID被发送。
removeFormElement(id) {
console.log('sending message up to remove id', id)
this.$emit('remove', id)
}
告诉父组件监听该事件并将函数附加到该事件。
<组件 v-for="字段中的字段"v-bind:is="field.type":id="field.id"@remove="removeFormElement":key="field.id">
请注意,@ 与 v-on 相同:
- 最后从 fields 数组中删除该项目。
removeFormElement(id) { console.log('removing form element', id) const index = this.fields.findIndex(f => f.id === id) this.fields.splice(index,1) }
关于javascript - 删除动态创建的 Vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54758812/