Home > Net >  Why isn't the prop defined?
Why isn't the prop defined?

Time:01-03

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 separate variable and setting its value to the props value because I thought the problem might be using the prop as a link directly.

CodePudding user response:

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>
  • Related