我按照此处创建动态表单元素的解决方案: Dynamically add different elements in Vue
效果很好,我的下一个难题是,如果用户添加太多表单元素,我想删除表单元素。
它的工作方式是用户创建一个“集”,该“集”被定义为一组输入。因此,每套可能适合不同的人或地点等。
这是我的 JSfiddle https://jsfiddle.net/61x784uv/
网页
<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>
Run Code Online (Sandbox Code Playgroud)
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++
});
},
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个工作小提琴:https://jsfiddle.net/e12hbLcr/
演练:
您需要为组件提供某种 id 才能知道应删除哪个组件。你可以用道具来做到这一点。
<组件 v-for="字段中的字段" v-bind:is="field.type" :id="field.id" :key="field.id">
现在在子组件中创建函数并编辑按钮,以便它发送 id。
<button v-on:click="removeFormElement(id)">删除输入</button>
请记住,在 Vue 中,props 向下(父 -> 子)而事件向上(子-父)。所以现在我们需要告诉父级这个按钮被点击并且一个 id 被发送了。
removeFormElement(id) {
console.log('sending message up to remove id', id)
this.$emit('remove', id)
}
Run Code Online (Sandbox Code Playgroud)
告诉父组件监听该事件并将函数附加到该事件。
<组件 v-for="字段中的字段" v-bind:is="field.type" :id="field.id" @remove="removeFormElement" :key="field.id">
请注意,@ 与 v-on 相同:
Run Code Online (Sandbox Code Playgroud)removeFormElement(id) { console.log('removing form element', id) const index = this.fields.findIndex(f => f.id === id) this.fields.splice(index,1) }
| 归档时间: |
|
| 查看次数: |
10794 次 |
| 最近记录: |