javascript - Vue.js 无法访问数据对象的嵌套属性

标签 javascript json vue.js vue-component

在 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 }} 或 {{ 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 所提到的,这是 fiddle :jsfiddle

最佳答案

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

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>

关于javascript - Vue.js 无法访问数据对象的嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41424354/

相关文章:

JavaScript:监听浏览器选项卡更改

javascript - 将由脚本插入和生成的 div 定位到其他元素上

PHP json_encode 生成带引号的 json 但 JS 希望它没有引号

javascript - 让 child 进入数组

javascript - Laravel - 让 vue 与其他插件一起工作

javascript - 如何在 Angular 中过滤数组?

php - 良好的 JSON 但浏览器抛出错误

java - 使用 for each loop 和 Map 创建 JSON 文件 - 它在 for 循环的所有迭代中重复第一个元素值

json - SoapUI - 如何通过 POST 请求使用 Property Transfer

vue.js - 初始化 VueX 商店不工作