You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中HTML访问多层级v-model嵌套元素报错的解决方法

解决Vue多层级v-model嵌套元素访问错误

问题根源

你的代码存在JavaScript语法错误,导致Vue实例无法正确初始化product数据对象,进而触发Cannot read properties of undefined (reading 'x1')错误:

  1. Vue.createApp的配置对象中,data选项的闭合}后缺少逗号(Vue配置选项间需用逗号分隔)
  2. 错误地将create.mount("#id_element")写在了Vue.createApp的配置对象内部,而非在实例外部调用mount方法

修正后的代码

HTML部分

<section id="id_element">
    <label for="x1">x1 </label>
    <input type="text" id="x1" v-model="product.xs.x1">
    <label for="x2">x2</label>
    <input type="text" id="x2" v-model="product.xs.x2">
</section>

JavaScript部分

<script>
const app = Vue.createApp({
    delimiters: ['[[', ']]'],
    data() {
        return {
            product : {
                xs: {
                    "x1" : "alpha",
                    "x2" : "beta"
                },
                ys: {
                    "y1": "one",
                    "y2": "two",
                    "y3": "three",
                    "y4": "four"
                }            
            }
        }
    }
});
app.mount("#id_element");
</script>

额外说明

  • 多层级v-model的写法product.xs.x1或product.xs['x1']都是正确的,核心问题是之前的语法错误导致数据未正确初始化
  • 若后续存在异步加载product数据的场景,可使用可选链操作符避免报错:v-model="product?.xs?.x1"(Vue 3原生支持该语法)

内容的提问来源于stack exchange,提问作者Moun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:03:26