Эх сурвалжийг харах

feat: 重构Google Ads集成为组件化方式

- 从nuxt.config.ts中移除Google Ads脚本配置
- 创建GoogleAd.vue组件封装广告逻辑
- 在index.vue页面中引入GoogleAd组件
bob 5 сар өмнө
parent
commit
547b09602a

+ 50 - 0
components/GoogleAd.vue

@@ -0,0 +1,50 @@
+<template>
+  <div v-if="!isPaidUser" class="ad-container">
+    <ins class="adsbygoogle"
+         style="display:block"
+         data-ad-client="ca-pub-9165036986914822"
+         data-ad-slot="YOUR_AD_SLOT_ID"
+         data-ad-format="auto"
+         data-full-width-responsive="true"></ins>
+  </div>
+</template>
+
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+
+// 在实际应用中,这里应该从您的状态管理库(如 Pinia)或 API 获取用户信息
+// 示例:const { isPaidUser } = useUserStore()
+const isPaidUser = ref(false) // 默认为非付费用户,显示广告
+
+// 加载 Google Ads 脚本 (如果尚未加载)
+const loadAdScript = () => {
+  if (typeof window !== 'undefined' && !document.querySelector('script[src*="adsbygoogle.js"]')) {
+    const script = document.createElement('script')
+    script.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9165036986914822"
+    script.async = true
+    script.crossOrigin = "anonymous"
+    document.head.appendChild(script)
+  }
+}
+
+onMounted(() => {
+  if (!isPaidUser.value) {
+    loadAdScript()
+    // 初始化广告
+    try {
+      // @ts-ignore
+      (window.adsbygoogle = window.adsbygoogle || []).push({});
+    } catch (e) {
+      console.error('AdSense error:', e)
+    }
+  }
+})
+</script>
+
+<style scoped>
+.ad-container {
+  margin: 20px 0;
+  text-align: center;
+  overflow: hidden;
+}
+</style>

+ 1 - 7
nuxt.config.ts

@@ -4,13 +4,7 @@ export default defineNuxtConfig({
   devtools: { enabled: true },
   app: {
     head: {
-      script: [
-        {
-          src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9165036986914822',
-          async: true,
-          crossorigin: 'anonymous'
-        }
-      ]
+      script: []
     }
   }
 })

+ 2 - 0
pages/index.vue

@@ -65,6 +65,8 @@
           <p>Bob</p>
         </div>
       </div>
+
+      <GoogleAd />
     </div>
 
     <div class="section letter">