【问题标题】:Why isn't the prop defined?为什么没有定义道具?
【发布时间】:2023-01-03 00:55:15
【问题描述】:

我的组件有以下代码:

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

但是我在 fetch-function 的行收到错误“'imgurl' is not defined”。我不明白为什么没有定义它,因为我在道具中将它定义为字符串。

任何帮助表示赞赏。

我也只尝试过制作一个单独的变量并将其值设置为道具值,因为我认为问题可能出在直接将道具用作链接。

【问题讨论】:

  • 你期望imgurl如何获得价值?它没有定义为变量或初始化为一个值。

标签: javascript vue.js error-handling vue-component


【解决方案1】:

我认为您将 &lt;script setup&gt; 表示法(使用组合 API)与选项 API 混合在一起。你可以这样做:

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

let imgLink = ref()

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

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

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

或者使用选项 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 2020-01-01
    • 2013-08-16
    • 1970-01-01
    • 2021-06-06
    • 2018-03-27
    • 2018-02-11
    相关资源
    最近更新 更多