Nuxt3中vueForm列表内联动选择框动态加载城市问题
VueForm列表组件中国家-城市动态联动解决方案
核心修改方案
针对列表内的联动场景,我们可以利用VueForm的组件上下文和同层级字段引用实现每个列表项独立的国家-城市联动:
城市选择框动态引用当前项的国家值
在城市字段的items配置中,直接使用同层级的{country}变量(VueForm会自动识别当前列表项的上下文,无需手动指定索引),若需调用API,直接拼接为myApi?country={country}即可。通过组件上下文定位当前列表项,独立更新城市选项
在国家选择框的onChange事件中,通过当前组件的$parent获取所属的列表项实例,再定位到对应的城市组件,仅更新当前项的城市选项,避免全局同步修改。
修改后的完整Schema代码
location: { "type": "list", "element": { "type": "object", "schema": { "country": { "columns": { "container": 6, }, "type": "select", "placeholder": "Country", "closeOnSelect": true, "items": [ { "value": "country1", "label": "Country 1", }, { "value": "country2", "label": "Country 2", }, ], "search": true, "native": false, "inputType": "search", "autocomplete": "off", "floating": false, // 新增onChange事件,仅更新当前列表项的城市选项 "onChange": async (val, component) => { // 获取当前列表项的实例 const listItem = component.$parent; // 获取当前项内的城市组件 const cityComponent = listItem.children$.find(el => el.key === 'city'); // 模拟API请求获取城市列表 const cities = await fetch(`myApi?country=${val}`) .then(res => res.json()) .catch(() => []); // 更新当前项的城市选项 cityComponent.schema.items = cities.map(city => ({ value: city.value, label: city.label })); } }, "city": { "columns": { "container": 6, }, "type": "select", "placeholder": "City", "closeOnSelect": true, // 直接引用同层级的country字段,自动适配当前列表项 "items": "myApi?country={country}", "search": true, "native": false, "inputType": "search", "autocomplete": "off", "floating": false, }, }, }, "addText": "Add another", "initial": 1, "min": 1, "max": 15, },
关键说明
- 同层级字段引用:在列表项的object schema内部,
{country}会自动指向当前项的country字段值,无需手动拼接location.<index>.country,VueForm会处理列表项的上下文隔离。 - 组件上下文定位:
onChange的第二个参数是当前国家选择框的组件实例,通过component.$parent可以获取到所属的列表项,再通过children$找到对应的城市组件,确保仅修改当前项的城市选项。 - 异步API处理:如果需要异步加载城市数据,直接在
onChange中使用async/await处理请求,更新对应组件的schema.items即可。
内容的提问来源于stack exchange,提问作者Hiba Salem
相关产品推荐
相关产品推荐

