Answer the question
In order to leave comments, you need to log in
How to change nested property via chaining in vue?
Hello!
There is an object:
const obj = {
a: '',
b: {
value: ''
}
}
const obj2 = [
{ model: 'a' }
{ model: 'b.value' }
]
<p v-for="item in obj 2" v-model="obj[model]">
Answer the question
In order to leave comments, you need to log in
computed: {
model() {
return new Proxy(Object.fromEntries(this.obj2.map(n => [ n.model, null ])), {
get: (target, prop) => typeof prop === 'string'
? prop.split('.').reduce((p, c) => p?.[c], this.obj)
: target[prop],
set: (target, prop, value) => {
const keys = prop.split('.');
const key = keys.pop();
const obj = keys.reduce((p, c) => (!p.hasOwnProperty(c) && this.$set(p, c, {}), p[c]), this.obj);
this.$set(obj, key, value);
return true;
},
});
},
},
<div v-for="(v, k) in model">
<input v-model="model[k]">
</div>
computed: {
model() {
return this.obj2.map(n => {
const keys = n.model.split('.');
const key = keys.pop();
const obj = keys.reduce((p, c) => p?.[c], this.obj);
return obj && { obj, key };
}).filter(Boolean);
},
},
<div v-for="n in model">
<input v-model="n.obj[n.key]">
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question