<template>
<page-head title="插屏广告"></page-head>
<button :type="btnType" style="margin: 10px;" :disabled="btnDisable" @click="showAd()">{{btnText}}</button>
<view v-for="(item,index) in errorDetails">{{item}}</view>
</template>
<script>
export default {
data() {
return {
errorDetails: [] as string[],
btnText: "",
btnType: "primary",
btnDisable: false,
interstitialAd: null as InterstitialAd | null,
isAdLoadSuccess: false
}
},
onReady() {
this.loadAd()
},
methods: {
loadAd() {
if (this.btnDisable)
return
this.btnDisable = true
this.btnText = "正在加载广告"
this.btnType = "primary"
if (this.interstitialAd == null) {
this.interstitialAd = uni.createInterstitialAd({
adpid: "1111111113" //此处为测试广告位,实际开发中请在uni-ad后台申请自己的广告位后替换
})
this.interstitialAd!.onError((res) => {
this.errorDetails.length = 0;
this.btnType = "warn"
this.btnDisable = false
this.btnText = res.errMsg;
const errors = (res.cause as UniAggregateError | null)?.errors;
if(errors != null && errors.length > 0) {
for(var a = 0;a<errors.length;a++) {
var msg = JSON.stringify(errors[a]);
this.errorDetails.push(msg);
}
}
})
this.interstitialAd!.onLoad((_) => {
this.errorDetails.length = 0;
this.btnType = "primary"
this.btnText = "广告加载成功,点击观看"
this.btnDisable = false
this.isAdLoadSuccess = true
})
this.interstitialAd!.onClose((_) => {
this.isAdLoadSuccess = false
this.loadAd()
})
}
this.interstitialAd!.load().catch(() => { })
},
showAd() {
if (this.isAdLoadSuccess) {
this.interstitialAd!.show().catch(() => { })
} else {
this.loadAd()
}
}
}
}
</script>
<style>
</style>