vue3 中如何添加google adsence

1,590 阅读1分钟

最近项目中涉及到google 广告代码,vue2中有插件 vue-google-adsense 不过目前这个插件还不支持vue3,所以用vue3 开发就存在问题,自己琢磨出以下方法,也可以

index.html

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxx"
    crossorigin="anonymous"></script>
...
<script>
    (adsbygoogle = window.adsbygoogle || []).push({});
</script>

adsense page:

<template>
  <div v-html="ads1"></div>
</template>
<script setup>
const ads1 = `
  <ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxx"
     data-ad-slot="xxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
`
</script>

亲测有效

另外一种方式就是把ins标签标记为自定义元素

mian.js

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.config.compilerOptions.isCustomElement = tag => tag.startsWith('ins')

app.mount('#app')