Why isn't the prop defined?

Advertisements

I have this code for my component:

<template>
    <h2>{{ name }}</h2>
    <img :src="imgLink"/>

</template>

<script>
import { ref } from 'vue';


let imgLink = ref()

export default {
    props: {
        'name': String,
        'imgurl': String
    }
}

fetch(imgurl).then(res => res.json()).then(json => imgLink.value = json.sprites.front_default)



</script>

But i get the error "’imgurl’ is not defined" at the line with the fetch-function. I don’t understand why it isn’t defined since i define it as a String in the props.

Any help is appreciated.

I have only tried too make a seperate variabel and setting its value to the props value becuase i thought the problem might be using the prop as a link directly.

>Solution :

I think you are mixin the <script setup> notation (using composition API) with the option API. You can either do :

<script setup>
import { ref, defineProps } from 'vue';

let imgLink = ref()

const props = defineProps({
  name: String,
  imgurl: String
})

fetch(props.imgurl).then(res => res.json()).then(json => imgLink.value = json.sprites.front_default)
</script>

See : https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits

Or with the options API :

<script>
export default {
    props: {
        'name': String,
        'imgurl': String
    },
    data: () => ({
       imgLink: null,
    }),
    created() {
        fetch(this.imgurl).then(res => res.json()).then(json => this.imgLink = json.sprites.front_default)
    }
}
</script>

Leave a ReplyCancel reply