My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correctly. I have inserted dummy data into the data store which is visible in my Vue Chrome dev tools plugin.
However, upon structuring the component as outlined below and attempting to load the page, an error message
Cannot read property 'amount' of undefined
is displayed in the console. It seems like this issue arises because the data loads before the computed properties are set in Vue.
I am contemplating various approaches but am aiming to seamlessly switch the displayed data when a tab is selected. One option would involve creating a separate component for each tab, although this could lead to redundant code.
Previous Attempts
- I attempted replacing currentObj: this.obj1
with currentObj: {}
in the data section, but encountered the same error.
- Moving the currentObj
data property to a computed property was another approach. While this allowed the page to load, the error persisted, and selecting tabs did not update the data.
Is there a method to effectively swap out the data in currentObj
within my component?
<template>
<div>
<ul class="tabs">
<li class="tab-title" v-on:click="tabSelection = 'tab1'">Tab 1</li>
<li class="tab-title" v-on:click="tabSelection = 'tab2'">Tab 2</li>
<li class="tab-title" v-on:click="tabSelection = 'tab3'">Tab 3</li>
</ul>
<div>{{ currentObj.amount }}</div>
</div>
<template>
<script>
export default {
data: function() {
return {
tabSelection: 'tab1',
currentObj: this.obj1
}
},
watch: {
tabSelection: function(oldTabSelection, newTabSelection) {
switch (newTabSelection) {
case 'tab1':
this.currentObj = this.obj1;
break;
case 'tab2':
this.currentObj = this.obj2;
break;
case 'tab3':
this.currentObj = this.obj3;
break;
}
}
},
computed: {
obj1: function() {
return this.$store.getters.obj1;
},
obj2: function() {
return this.$store.getters.obj2;
},
obj3: function() {
return this.$store.getters.obj3;
}
}
}
</script>