【问题标题】:Vue.js cannot access to nested properties of data objectVue.js 无法访问数据对象的嵌套属性
【发布时间】:2017-05-16 09:56:53
【问题描述】:

在 Vue.js 中,我获取 json 文件的一些数据,如下所示:

export default {
    data () {
       return {
           data: []
       }   
    },
    created () {
        this.fetchData();    
    },
    methods: {
        fetchData () {
            $.getJSON('data/api.json', function(el) {
                this.data = el;
            }.bind(this)),
        }
    }
}

获取的数据结构如下:

{
    time: '17:00',
    pick: {
        box: {
            single: 1,
            multi: 2
        }    
    }
}

当我尝试在我的组件中访问 {{ data.pick.box }} or {{ data.pick.box.single }} 时,我总是收到以下错误消息:

vue.js?3de6:2963 Uncaught TypeError: Cannot read property 'box' of undefined
at Proxy.render (eval at <anonymous> (app.js:126), <anonymous>:4:46)
at VueComponent.Vue._render (eval at <anonymous> (app.js:139), <anonymous>:2954:22)
at VueComponent.eval (eval at <anonymous> (app.js:139), <anonymous>:2191:21)
at Watcher.get (eval at <anonymous> (app.js:139), <anonymous>:1656:27)
at new Watcher (eval at <anonymous> (app.js:139), <anonymous>:1648:12)
at VueComponent.Vue._mount (eval at <anonymous> (app.js:139), <anonymous>:2190:19)
at VueComponent.Vue$3.$mount (eval at <anonymous> (app.js:139), <anonymous>:5978:15)
at VueComponent.Vue$3.$mount (eval at <anonymous> (app.js:139), <anonymous>:8305:16)
at init (eval at <anonymous> (app.js:139), <anonymous>:2502:11)
at createComponent (eval at <anonymous> (app.js:139), <anonymous>:4052:9)

访问深层嵌套对象是否有任何限制?例如,当我调用{{ data }} 时,我将整个数据结构正确显示为字符串。

正如 Nora 所说,这里是小提琴:jsfiddle

【问题讨论】:

  • 你能设置一个 jsfiddle 吗?
  • 第一次渲染时data[],并且没有任何.pick.box属性。
  • 如果您不想使用额外的变量,可以使用我在回答中提到的v-if

标签: javascript json vue.js vue-component


【解决方案1】:

您可以尝试等待数据完成加载以将其显示在您的模板中:

export default {
    data () {
       return {
           loading: false,
           data: []
       }   
    },
    created () {
        this.fetchData();    
    },
    methods: {
        fetchData () {
            this.loading = true;
            $.getJSON('data/api.json', function(el) {
                this.data = el;
                this.loading = false;
            }.bind(this)),
        }
    }
}

在模板中:

<template>
  <div v-if="!loading">
    {{ data.pick.box }}
  </div>
</template>

【讨论】:

  • 我遇到了同样的问题,但这个解决方案对我不起作用。我刚刚将生命周期钩子从 mount() 更改为 create() 并且它起作用了。无论如何,谢谢!
【解决方案2】:

您收到此错误,因为 data 在加载时未填充,并且您在此期间收到错误。您可以在模板中使用v-if,直到数据填充到视图中。所以元素在数据加载之前不会被渲染,一旦数据加载它就会显示数据。

可以是这样的:

<div v-if="data.pick">
  {{data.pick.box}}
</div>

【讨论】:

  • 爱简单的解决方案
  • 如果您对该嵌套对象有多次调用,这将不起作用
  • 让我免于很多麻烦
【解决方案3】:

我的解决方案是创建一个具有空属性的空对象。

 data () {
       return {
           loading: false,
           data: {pick:{},}
       }   
    },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多