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

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

获取的数据具有以下 struct :

{
    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 }}时,我将整个数据 struct 正确地显示为字符串.

正如诺拉所说,这是小提琴:jsfiddle

推荐答案

您可以try 等待数据加载完成,然后将其显示在模板中:

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>

Vue.js相关问答推荐

当props 的值改变时如何更新类'

在VITE-VUE APP-DEV模式上重定向HTTP请求

在vuejs中使用表单追加时如何使用布尔值

如何在vue js模板中添加foreach和for循环

Shopware 6,使用 vue-test-utils 进行Jest 测试:渲染模板上的意外行为

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

如何解决 importers[path] is not a function for clean Vue 3/Vite/Storybook installation

如何在 Nuxt3 中使用 nuxtjs/auth-next 模块?

如何在 VUE.js 中重新刷新时保持多层 b-collapse 菜单打开?

Vue:将点击事件绑定到动态插入的内容

我是否必须在 Vue 3 中使用 Composition API,还是仍然可以使用Vue 2的方式工作?

从组件的 内的组件调用方法

Vue.js 中的 mount挂载是什么意思?

如何使 Rails 与 vue.js 一起工作?

Vue.js 如何计算总数?

在 vuejs 中的图像中包含 router-link 标记

即使在客户端设置 Access-Control-Allow-Origin 或其他 Access-Control-Allow-* 标头后也出现 CORS 错误

在组件之间共享数据

Vuetify - 如何进行分页?

Vue 2.0 设置路由 - 不要使用new来产生副作用