I am encountering an issue with my Vue component. Here is the code for reference:
Vue.component('result', {
props: ['stuff'],
data: () => ({}),
template: "<img :src='tag' class='result'></img>",
computed: {
tag: function() {
return `pages/search/img/${this.stuff.type.toLowerCase()}_tag.png`;
}
}
});
Upon creating the component, I receive an error message:
TypeError: Cannot read property 'toLowerCase' of undefined
at VueComponent.tag
Strange enough, without using toLowerCase()
, the method functions correctly and generates the expected string. I could potentially adjust my file names to avoid this issue, but I am more interested in understanding why Vue is behaving like this. Why does a property become undefined only when methods are invoked on it?
Update: Further investigation revealed that this.stuff.type
is indeed undefined during the initial computation of tag()
. The usage of toLowerCase()
simply exposes an error in what would have otherwise been a silent bug. Is there a specific reason why props
are not defined when accessed from within a computed
function for the first time? Should I be structuring my component differently?