GoogleAd.vue 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <template>
  2. <div v-if="!isPaidUser" class="ad-container">
  3. <ins class="adsbygoogle"
  4. style="display:block"
  5. data-ad-client="ca-pub-9165036986914822"
  6. data-ad-slot="YOUR_AD_SLOT_ID"
  7. data-ad-format="auto"
  8. data-full-width-responsive="true"></ins>
  9. </div>
  10. </template>
  11. <script setup lang="ts">
  12. import { ref, onMounted } from 'vue'
  13. // 在实际应用中,这里应该从您的状态管理库(如 Pinia)或 API 获取用户信息
  14. // 示例:const { isPaidUser } = useUserStore()
  15. const isPaidUser = ref(false) // 默认为非付费用户,显示广告
  16. // 加载 Google Ads 脚本 (如果尚未加载)
  17. const loadAdScript = () => {
  18. if (typeof window !== 'undefined' && !document.querySelector('script[src*="adsbygoogle.js"]')) {
  19. const script = document.createElement('script')
  20. script.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9165036986914822"
  21. script.async = true
  22. script.crossOrigin = "anonymous"
  23. document.head.appendChild(script)
  24. }
  25. }
  26. onMounted(() => {
  27. if (!isPaidUser.value) {
  28. loadAdScript()
  29. // 初始化广告
  30. try {
  31. // @ts-ignore
  32. (window.adsbygoogle = window.adsbygoogle || []).push({});
  33. } catch (e) {
  34. console.error('AdSense error:', e)
  35. }
  36. }
  37. })
  38. </script>
  39. <style scoped>
  40. .ad-container {
  41. margin: 20px 0;
  42. text-align: center;
  43. overflow: hidden;
  44. }
  45. </style>