0

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

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

Data JSON

This file contains several projects

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

Router

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

Component 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')
      })
  }
}

Component HTML

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

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

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

2

1 Answer 1

2

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" />

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.