Consider the following data structure:
rules:[
0:{
subrule1:'',
subrule2:'',
subrule3:''
},
1:{
subrule1:'',
subrule2:'',
subrule3:''
}
]
and it can be iterated through like this:
<div v-for="(fields, index) in rules" :key="index">
<div>
<button @click.prevent="addMore()">
Add Rules
</button>
</div>
<div>
<button @click.prevent="deleteSubrule(index)">
Delete
</button>
</div>
<input
name="subrule1"
:value="getAdditionalIndex(index, 'subrule1')"
/>
<input
name="subrule2"
:value="getAdditionalIndex(index, 'subrule2')"
/>
<input
name="subrule3"
:value="getAdditionalIndex(index, 'subrule3')"
/>
</div>
The corresponding methods are:
getAdditionalIndex(index, field) {
return this.rules[index][field];
},
addMore(){
const fields = {
subrule1:'',
subrule2:'',
subrule3:''
};
this.rules.push(fields)
},
deleteSubrule(index){
this.$delete(this.rules, index)
}
However, there might be issues with data binding and deletion errors. Deep watchers are usually used with child components but not directly on v-for elements. Is there a solution that allows deep watchers in this context?
Below is a runnable snippet for reference:
<html>
<div id="app">
<div>
<button @click.prevent="addMore()">
Add Rules
</button>
</div>
<div>
<button @click.prevent="showStates()">
Show state results
</button>
</div>
<div v-for="(fields, index) in rules" :key="index">
<div>
<button @click.prevent="deleteSubrule(index)">
Delete
</button>
</div>
<input
name="subrule1"
:value="getAdditionalIndex(index, 'subrule1')"
@input="inputChange"
/>
<input
name="subrule2"
:value="getAdditionalIndex(index, 'subrule2')"
@input="inputChange"
/>
<input
name="subrule3"
:value="getAdditionalIndex(index, 'subrule3')"
@input="inputChange"
/>
</div>
</div>
<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
new Vue({
el: '#app', //Tells Vue to render in HTML element with id "app"
data() {
return {
rules:[],
test:''
}
},
methods:{
addMore(){
const fields = {
subrule1:'',
subrule2:'',
subrule3:''
};
this.rules.push(fields)
},
deleteSubrule(index){
this.$delete(this.rules, index)
},
getAdditionalIndex(index, field) {
return this.rules[index][field];
},
inputChange(event){
return event.target.value
},
showStates(){
alert(JSON.stringify(this.rules))
}
}
});
</script>
</html>