create-rewarded-video-ad.uvue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. rewardAd: null as RewardedVideoAd | null,
  15. isAdLoadSuccess: false
  16. }
  17. },
  18. onReady() {
  19. this.loadAd()
  20. },
  21. onHide() {
  22. console.log("Page Hide");
  23. },
  24. methods: {
  25. loadAd() {
  26. if (this.btnDisable)
  27. return
  28. this.btnDisable = true
  29. this.btnText = "正在加载广告"
  30. this.btnType = "primary"
  31. if (this.rewardAd == null) {
  32. this.rewardAd = uni.createRewardedVideoAd({
  33. adpid: "1507000689" //此处为测试广告位,实际开发中请在uni-ad后台申请自己的广告位后替换
  34. })
  35. this.rewardAd!.onError((res) => {
  36. this.errorDetails.length = 0;
  37. this.btnType = "warn"
  38. this.btnDisable = false
  39. this.btnText = res.errMsg;
  40. const errors = (res.cause as UniAggregateError|null)?.errors;
  41. if(errors != null && errors.length > 0) {
  42. for(var a = 0;a<errors.length;a++) {
  43. var msg = JSON.stringify(errors[a]);
  44. this.errorDetails.push(msg);
  45. }
  46. }
  47. })
  48. this.rewardAd!.onLoad((_) => {
  49. this.errorDetails.length = 0;
  50. this.btnType = "primary"
  51. this.btnText = "广告加载成功,点击观看"
  52. this.btnDisable = false
  53. this.isAdLoadSuccess = true
  54. })
  55. this.rewardAd!.onClose((e) => {
  56. // 测试广告位无法通过服务器回调。实际开发中,使用自己的广告位后,需参考uni-ad文档编写服务器回调的代码,在服务端发放奖励
  57. this.isAdLoadSuccess = false
  58. uni.showToast({
  59. title: "激励视频" + (e.isEnded ? "" : "未") + "播放完毕",
  60. position: "bottom"
  61. })
  62. this.loadAd()
  63. })
  64. }
  65. this.rewardAd!.load().catch(()=>{})
  66. },
  67. showAd() {
  68. if (this.isAdLoadSuccess) {
  69. this.rewardAd!.show().catch(()=>{})
  70. } else {
  71. this.loadAd()
  72. }
  73. }
  74. }
  75. }
  76. </script>
  77. <style>
  78. </style>