create-interstitial-ad.uvue 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <template>
  2. <page-head title="插屏广告"></page-head>
  3. <button :type="btnType" style="margin: 10px;" :disabled="btnDisable" @click="showAd()">{{btnText}}</button>
  4. <view v-for="(item,index) in errorDetails">{{item}}</view>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. errorDetails: [] as string[],
  11. btnText: "",
  12. btnType: "primary",
  13. btnDisable: false,
  14. interstitialAd: null as InterstitialAd | null,
  15. isAdLoadSuccess: false
  16. }
  17. },
  18. onReady() {
  19. this.loadAd()
  20. },
  21. methods: {
  22. loadAd() {
  23. if (this.btnDisable)
  24. return
  25. this.btnDisable = true
  26. this.btnText = "正在加载广告"
  27. this.btnType = "primary"
  28. if (this.interstitialAd == null) {
  29. this.interstitialAd = uni.createInterstitialAd({
  30. adpid: "1111111113" //此处为测试广告位,实际开发中请在uni-ad后台申请自己的广告位后替换
  31. })
  32. this.interstitialAd!.onError((res) => {
  33. this.errorDetails.length = 0;
  34. this.btnType = "warn"
  35. this.btnDisable = false
  36. this.btnText = res.errMsg;
  37. const errors = (res.cause as UniAggregateError | null)?.errors;
  38. if(errors != null && errors.length > 0) {
  39. for(var a = 0;a<errors.length;a++) {
  40. var msg = JSON.stringify(errors[a]);
  41. this.errorDetails.push(msg);
  42. }
  43. }
  44. })
  45. this.interstitialAd!.onLoad((_) => {
  46. this.errorDetails.length = 0;
  47. this.btnType = "primary"
  48. this.btnText = "广告加载成功,点击观看"
  49. this.btnDisable = false
  50. this.isAdLoadSuccess = true
  51. })
  52. this.interstitialAd!.onClose((_) => {
  53. this.isAdLoadSuccess = false
  54. this.loadAd()
  55. })
  56. }
  57. this.interstitialAd!.load().catch(() => { })
  58. },
  59. showAd() {
  60. if (this.isAdLoadSuccess) {
  61. this.interstitialAd!.show().catch(() => { })
  62. } else {
  63. this.loadAd()
  64. }
  65. }
  66. }
  67. }
  68. </script>
  69. <style>
  70. </style>