vue实现开屏广告
Vue 实现开屏广告的方法
在 Vue 中实现开屏广告通常涉及创建一个全屏覆盖的广告组件,并在应用加载时显示一段时间后自动关闭。以下是具体实现方法。
创建广告组件
创建一个独立的广告组件,例如 SplashAd.vue。该组件包含广告图片或视频,并设置全屏样式。

<template>
<div class="splash-ad" v-if="show">
<img src="@/assets/ad.jpg" alt="广告" @click="handleClick" />
<button @click="closeAd">跳过</button>
</div>
</template>
<script>
export default {
data() {
return {
show: true,
timer: null
};
},
mounted() {
this.timer = setTimeout(() => {
this.closeAd();
}, 3000); // 3秒后自动关闭
},
methods: {
closeAd() {
this.show = false;
clearTimeout(this.timer);
},
handleClick() {
// 点击广告跳转逻辑
window.location.href = 'https://example.com';
}
},
beforeDestroy() {
clearTimeout(this.timer);
}
};
</script>
<style scoped>
.splash-ad {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
}
.splash-ad img {
max-width: 100%;
max-height: 100%;
}
.splash-ad button {
position: absolute;
top: 20px;
right: 20px;
padding: 5px 10px;
background: rgba(0, 0, 0, 0.5);
color: #fff;
border: none;
border-radius: 4px;
}
</style>
在根组件中引入广告
将广告组件放置在根组件(如 App.vue)中,确保广告在其他内容之前加载。

<template>
<div id="app">
<SplashAd />
<router-view />
</div>
</template>
<script>
import SplashAd from '@/components/SplashAd.vue';
export default {
components: {
SplashAd
}
};
</script>
使用路由控制广告显示
如果需要在特定页面显示广告,可以通过路由守卫控制广告的显示逻辑。
// router.js
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = new Router({
routes: [
// 路由配置
]
});
router.beforeEach((to, from, next) => {
if (to.meta.showAd) {
// 显示广告逻辑
}
next();
});
export default router;
广告数据动态加载
从后端 API 动态加载广告内容,使广告可配置化。
// SplashAd.vue
export default {
data() {
return {
adImage: '',
adUrl: ''
};
},
mounted() {
this.fetchAdData();
},
methods: {
async fetchAdData() {
try {
const response = await axios.get('/api/ad');
this.adImage = response.data.image;
this.adUrl = response.data.url;
} catch (error) {
console.error('加载广告失败', error);
}
}
}
};
注意事项
- 广告组件应设置为最高层级(
z-index),避免被其他元素遮挡。 - 清除定时器防止内存泄漏。
- 考虑移动端和桌面端的适配问题。
- 广告关闭后可以通过本地存储(如
localStorage)记录已显示状态,避免频繁显示。
通过以上方法,可以在 Vue 项目中实现一个灵活的开屏广告功能。






