无法访问我的Vue组件中的嵌套JSON数据 [英] Can't access nested JSON data in my Vue Component

查看:506
本文介绍了无法访问我的Vue组件中的嵌套JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚为什么我似乎无法在Vue组件中访问以下JSON数据.

Im trying to figure out why I can't seem to access the following piece of JSON data in my Vue Component.

我的项目是使用带有Webpack模板的Vue-cli进行设置的,遇到问题时,其设置大致如下.

My project is setup using Vue-cli with the Webpack template and is roughly setup as follows when I run into the problem.

此文件包含多个项目

projects: [
  {
    "slug": "page-url-slug",
    "title": "Page title",
    "image": {
      "src": "/static/images/project-image.jpg",
      "alt": "Alt text image"
    }
  }
]

路由器

routes: [
  {
    path: '/work'
    component: Work
  },
  {
    path: '/work/:slug',
    component: WorkItem,
    props: (route) => ({
      params: route.params
    })
  }
]

组件JS

export default {
  props: [ 'params' ],

  data () {
    return {
      project: {}
    }
  },

  mounted () {
    this.$http.get('/static/data.json')
      .then((response) => {
        let projects = response.data.projects

        // Find data with same slug param
        for (let i = 0; i < projects.length; i++) {
          if (projects[i].slug === this.params.slug) {
            this.project = projects[i]
            return
          }
        }

        // Else go back to parent route
        this.$router.push('/work')
      })
  }
}

组件HTML

<template lang="html">
  <div class="page">
    <h1>{{ project.title }}</h1>
    <img :src="project.image.src" alt="project.image.alt" />
  </div>
</template>

当我尝试访问 project.image.src project.image.alt 时,我不断收到以下错误消息:

When I try to access the project.image.src or the project.image.alt I keep getting the following error messages:

[Vue warn]: Error when rendering anonymous component at ...

Uncaught TypeError: Cannot read property 'src' of undefined

我对Vuejs来说还很陌生,我似乎无法完全意识到这种情况的发生.

I am pretty new to Vuejs and I just can't seem to wrap my mind around the fact this happens.

推荐答案

在异步加载project时,您必须添加null检查,如下所示:

You have to add null check as you are loading project asynchronously, like this:

<img :src="project && project.image && project.image.src" alt="project.image.alt" />

渲染时,当时没有填充project,它仍然是{},您可以在开始时对其进行设置.

When this is being rendered, at that time project is not populated and it is still {}, which you set it in the beginning.

这篇关于无法访问我的Vue组件中的嵌套JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆