我想打开或关闭一个覆盖组件,使用一个方法toggleOverlay()来改变布尔showOverlay。但是我很困惑,网络上的许多例子看起来都是一样的,而且很有用。但是我的版本没有。在这个方法中,我不能访问数据,因为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>发布于 2022-10-11 14:43:22
我被所有的例子搞糊涂了,都是基于没有打字记录的Vue。但我终于看到了我的错误。完全忽略了setup()函数的defineComponent()方法。它也更简单一些。
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>https://stackoverflow.com/questions/74029292
复制相似问题