gpt4 book ai didi

javascript - 如何使用点分隔字符串作为 vue v-model 指令的对象路径

转载 作者:行者123 更新时间:2023-12-05 03:34:16 25 4
gpt4 key购买 nike

我有数据记录

record: {
address: {
city: ""
}
}

描述字段的对象数组

fields: [ 
{
name: "address.city"
...
}
]

并尝试生成表单

    <b-field
v-for="field in fields"
:key="field.name"
:label="field.label"
>
<b-input v-model="record[field.name]" />
</b-field>

并使用 address.name 之类的键获取对象项我知道我应该传递给 v-model record[address][city] 但如何从点分隔字符串中传递?

这可能吗?

最佳答案

const getPathInObject = (path, object) => {
const [current, ...rest] = path.split('.')
return rest.length === 0
? object[current]
: getPathInObject(rest.join('.'), object[current])
}

document.write(getPathInObject('a.b.c.d', { a: { b: { c: { d: 'hello' } } } }))
编辑 可能是这样的。虽然很老套

const unflatten = obj => {
const result = {};
Object.entries(obj).forEach(([key, value]) => {
const [a, b] = key.split('.');
result[a] ||= {};
result[a][b] = value
})
return result
}


new Vue({
el: "#app",
data: {
record_flat: {"address.city": '', "address.country": ''},
fields: [
{ name: "address.city", label: 'city' },
{ name: "address.country", label: 'country' }
]
},
computed: {
record: ({ record_flat }) => unflatten(record_flat),
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="{name, label} in fields" :key="name">
<label>{{ label }}</label><input v-model="record_flat[name]" />
<br>
</div>
<hr>Value of record = {{ record }}
</div>

关于javascript - 如何使用点分隔字符串作为 vue v-model 指令的对象路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70215277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com