vue3双向绑定嵌套的JSON最佳实践
我有以下REST API的JSON响应
{
"data": {
"name": "data 123",
"prop1" : "abc",
"prop2" : "xyz",
"contacts": [
{
"id" : 1
"name": "person 1",
"address": {
"city": "London",
"zipcode": "1234",
"street": "Demostreet",
"housenumber": "123"
}
},
{
.....
}
]
}
}
现在,假设我想将第一个联系人的ZipCode绑定到输入字段。 从我的角度来看,我有两个选项:
用setter编写一个计算机属性,并为JSON中的每个属性的输入V模型进行获取,我想为用户编辑 这样我就可以简单地将相同的json
aka发送回类似的东西
computed: {
zipcode: {
get(){
let contact = this.form.contacts?.find(f => f.id == 1);
if (contact != undefined)
return contact.address.zipcode;
else
return "";
},
set(val){
let contact = this.form.contacts?.find(f => f.id == 1);
contact.address.zipcode = val;
}
}
}
,也可以写下简化的本地扁平登录JSON-直接将其绑定到输入V -Model,然后在单击“保存”时将其映射到接收的JSON。
{
"data":{
"name": "data 123",
"prop1" : "abc",
"prop2" : "xyz",
"city1": "London",
"zipcode1": "1234",
"street1": "Demostreet",
"housenumber1": "123"
}
}
如此深的JSON双向绑定的最佳实践是什么? 我想念什么吗?
我不喜欢这两个选择
i have the following JSON response from a REST API
{
"data": {
"name": "data 123",
"prop1" : "abc",
"prop2" : "xyz",
"contacts": [
{
"id" : 1
"name": "person 1",
"address": {
"city": "London",
"zipcode": "1234",
"street": "Demostreet",
"housenumber": "123"
}
},
{
.....
}
]
}
}
now let's say i want to bind the first contact's ZIPCODE to a input field.
from my point of view i've got two options:
write a computed property with a setter and a getter for the input v-model for EVERY property in the JSON that i want to be editable for the user
so that i can simply send back the same JSON
aka something like that
computed: {
zipcode: {
get(){
let contact = this.form.contacts?.find(f => f.id == 1);
if (contact != undefined)
return contact.address.zipcode;
else
return "";
},
set(val){
let contact = this.form.contacts?.find(f => f.id == 1);
contact.address.zipcode = val;
}
}
}
or write a simplified local flattenend down JSON - bind it directly to the input v-model and map it to the received JSON when clicking SAVE.
{
"data":{
"name": "data 123",
"prop1" : "abc",
"prop2" : "xyz",
"city1": "London",
"zipcode1": "1234",
"street1": "Demostreet",
"housenumber1": "123"
}
}
what's the best practice for such deep nested json two way binding?
am i missing something?
i don't like both options
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论