Reputation: 3
I created an application which uses axios (+vue-axios) to get data from JSON file to Vuex store. I also use Vue-Router for different views for my application.
App.vue
) I display <router-view>
Slides.vue
When 2. is created()
I do
created(): {
this.$http.get('./static/data/slides.json')
.then(({ data }) => {
this.$store.state.slides = data;
})
.catch((error) => {
console.log(error);
});
},
In that component (Slides.vue
) have Slide.vue
component which get :slides="slides"
prop:
<Slide :slides="slides" />
Inside Slide.vue
I have in <script>
:
props: ['slides'],
computed: {
slideId() { return this.$store.state.activeSlide; },
slide() { return this.slides[this.slideId]; },
slideTitle() { return this.slide.title; },
},
In <template>
i use {{ slideTitle }}
to display title
When I try to run this, I have an error in Slide.vue
:
[Vue warn]: Error in render: "TypeError: this.slide is undefined"
Why is this happening?
When I change this.slide.title
to this.slide
it seems to work (but display all data from JSON file which is not what I want)
Upvotes: 0
Views: 425
Reputation: 6788
I believe that the problem is related to this.slideId
being undefined before the created()
call to the store is resolved -or at anytime-. This causes the computed property slide
to be undefined
-since it resolves to this.slides[undefined]
.
At the end, the computed property slideTitle
resolves to undefined.title
, thus throwing an error.
If I am right, you can overpass this problem by modifying your slideTitle()
computed property as follows:
slideTitle() { return this.slide && this.slide.title; }
Said so, there is a problem in your created()
hook, when you do:
this.$store.state.slides = data;
You're manipulating the store state directly. This is forbidden by vuex and will cause all kind of errors. Instead, you should use a mutation to modify the store state.
Upvotes: 1