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.