user3382908
user3382908

Reputation: 3

Why my computed is undefined

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.

  1. In my main component (App.vue) I display <router-view>
  2. My view component is Slides.vue
  3. 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);
        });
    },
    
  4. In that component (Slides.vue) have Slide.vue component which get :slides="slides" prop:

    <Slide :slides="slides" />
    
  5. 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; },
    },
    
  6. 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

Answers (1)

Sergeon
Sergeon

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

Related Questions