0👍
If you work out the structure you want to keep your data, then you don’t need to mess with DOM elements: just add the JSON to the data()
& let Vue do its thing.
So, if you take the JSON data structure as the base for the form fields & fieldsets, then you can just add it to the data item holding the form input fields:
const example = {
"Username": "",
"Password": "",
"AffiliateID": "",
"GI": "",
"CI": "",
"freeTextArea": ""
}
Vue.component("formFieldset", {
props: ["fields"],
methods: {
handleInput(val, key) {
this.$emit("update:fields", { key, val })
},
},
template: `
<div>
<label
v-for="(val, key) in fields"
:key="key"
>
{{ key }}:
<input
type="text"
:placeholder="key"
@input="(e) => handleInput(e.target.value, key)"
/>
</label>
<hr>
</div>
`
})
new Vue({
el: "#app",
data() {
return {
fieldsets: [
{
field1_1: "",
field1_2: "",
},
{
field2_1: "",
field2_2: "",
},
],
}
},
// just to add the items later to the data():
mounted() {
this.fieldsets.push(example)
},
methods: {
handleUpdateFields({ key, val, idx }) {
this.fieldsets[idx][key] = val
},
},
template: `
<div>
Putting out the data():<br />
{{ fieldsets }}
<hr>
<form>
<form-fieldset
v-for="(fieldset, i) in fieldsets"
:key="i"
:fields="fieldset"
@update:fields="(e) => handleUpdateFields({...e, idx: i})"
/>
</form>
</div>
`
})
label {
display: block;
padding: 8px 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
Source:stackexchange.com