Files
spring-festival-greetings/components/RewardAd/RewardAd.vue
2026-02-25 09:54:41 +08:00

76 lines
1.5 KiB
Vue

<template>
<view></view>
</template>
<script setup>
import { onMounted, onUnmounted } from "vue";
const props = defineProps({
adUnitId: {
type: String,
default: "adunit-d7a28e0357d98947",
},
});
const emit = defineEmits(["onReward", "onError", "onClose"]);
let videoAd = null;
const onLoadHandler = () => {
console.log("Ad Loaded");
};
const onErrorHandler = (err) => {
console.error("Ad Load Error", err);
emit("onError", err);
};
const onCloseHandler = (res) => {
if (res && res.isEnded) {
emit("onReward");
} else {
uni.showToast({ title: "观看完整广告才能获取奖励哦", icon: "none" });
emit("onClose");
}
};
onMounted(() => {
if (uni.createRewardedVideoAd) {
videoAd = uni.createRewardedVideoAd({
adUnitId: props.adUnitId,
});
videoAd.onLoad(onLoadHandler);
videoAd.onError(onErrorHandler);
videoAd.onClose(onCloseHandler);
}
});
onUnmounted(() => {
if (videoAd) {
videoAd.offLoad(onLoadHandler);
videoAd.offError(onErrorHandler);
videoAd.offClose(onCloseHandler);
}
});
const show = () => {
if (videoAd) {
videoAd.show().catch(() => {
videoAd
.load()
.then(() => videoAd.show())
.catch((err) => {
console.error("Ad show failed", err);
uni.showToast({ title: "广告加载失败,请稍后再试", icon: "none" });
emit("onError", err);
});
});
} else {
uni.showToast({ title: "当前环境不支持广告", icon: "none" });
}
};
defineExpose({ show });
</script>