[Vuejs]-Cant seem to load vuejs component, TypeError: "this.kitChens.find(…) is undefined"

1👍

There are many problems here…

Firstly, kitChen with a capital C in the middle? I don’t know why you’ve done that but any future maintainers of your code will appreciate you sticking to correct spelling and standard use of capital letters.

Likewise you need to sort out your indentation. It’s all over the place. While it may not prevent the code from working it does prevent other developers from being able to understand it.

The next problem is your kitchenImage property. Initially the array kitChens will be empty, so it won’t find anything. find will return undefined and then the attempt to access the property kitchen_type_pic will fail. You need something like this:

computed: {
  kitchenImage() {
    const kitchen = this.kitChens.find(el => el.id == this.selectedKitchen)

    return kitchen && kitchen.kitchen_type_pic
  }
}

Here I’ve assumed it is acceptable for kitchenImage to be undefined.

Then there are several problems in your template:

<img class="-block w-100" :src="'/../../images/' + kitchenImage()" :alt="'{{ kitChen.kitchen_type}}'" />

kitchenImage is a computed property, not a method, so you don’t need the () on the end. It’ll also need a v-if to handle the case where kitchenImage is undefined. It may be that it makes more sense for that v-if to be higher up, it’s difficult for me to know what the correct behaviour should be in that case.

There’s also the problem of the alt. I’m not even sure what that’s trying to do.

I think you’re aiming for something like this:

<img
  v-if="kitchenImage"
  class="-block w-100"
  :src="'/../../images/' + kitchenImage"
  :alt="kitChen.kitchen_type"
/>

However, for this to work it will need kitChen.kitchen_type to exist and I don’t see anything in your original code to suggest that it does. I suspect what you want is a similar computed property to kitchenImage that returns the kitchen_type instead of the kitchen_type_pic.

0👍

You are calling kitchenImage() on template load.

Which runs your Find() function, which then in return will try to find a select kitty with the ID of 0, which i assume is undefined.

The solution is:

Set a default ‘selectedKitchen’ value.

Or..

structure your code so your function doesnt run untill a kitty has actually been selected. This can be done but changing your computed function to a method. Then running it Onclick https://v2.vuejs.org/v2/guide/events.html

Special note: I thought it was kitty’s this whole time reading the
code and not, kitchen, but im going to leave this in

Leave a comment