使用Vue3 defineComponent方法无法访问数据属性,data=undefined



我想使用更改布尔值showOverlay的方法toggleOverlay()打开或关闭覆盖组件。但我感到困惑,网络上的许多例子看起来都一样,而且有效。但我的版本没有。在这种方法中,我无法访问数据,因为this是未定义的。

<script lang="ts">
import { defineComponent } from 'vue';
import TrendingTVShow from '@/components/TrendingTVShow.vue';
import TVShowOverlay from '@/components/TVShowOverlay.vue';
import type { Show } from "@/tvAppTypes";
export default defineComponent({
components: {
TrendingTVShow, TVShowOverlay,
},
methods: {
toggleOverlay: (): void => {
console.log(this); // = undefined ???
this.showOverlay = !this.showOverlay; // Flip the BOOLEAN, show or hide <TVShowOverlay>
console.log(showOverlay); // Unhandled error during execution of native event handler at <TrendingTVShow onClick=fn<bound toggleOverlay> tvShow= 
},
},
props: {
tvShows: {
type: Array<Show>,
required: true,
},
},
data() {
return {
showOverlay: false,
};
},
});
</script>
<template>
<main>
<TrendingTVShow @click="toggleOverlay" :tvShow="tvShow[0]"></TrendingTVShow>
<TVShowOverlay v-if="showOverlay" :tvShow="tvShow[0]" :toggle="toggleOverlay"></TVShowOverlay>
</main>
</template>

我对所有基于Vue而没有Typescript的示例感到困惑。但我终于看到了自己的错误。完全忽略了defineComponent()函数的setup()方法。它也更简单。

export default defineComponent({
components: {
TrendingTVShow, TVShowOverlay,
},
props: {
tvShows: {
type: Array<Show>, // Object as PropType<Show>,
required: true,
},
},
setup( props ): any {
const randomShow = props.tvShows[Math.floor(Math.random() * props.tvShows.length)];
const showOverlay = ref<boolean>();
const toggleOverlay = () => {
showOverlay.value = !showOverlay.value;
}
showOverlay.value = false;
return { randomShow, toggleOverlay, showOverlay }
}
});
</script>
<template>
<main>
<h1>On air now</h1>
<TrendingTVShow @click="toggleOverlay" :tvShow="randomShow"></TrendingTVShow>
<TVShowOverlay v-if="showOverlay" :tvShow="randomShow" :toggle="toggleOverlay"></TVShowOverlay>
</main>
</template>

相关内容

最新更新