vue实现开屏广告
实现开屏广告的基本思路
在Vue中实现开屏广告通常需要结合路由守卫、定时器和本地存储技术。核心逻辑包括广告显示、倒计时控制以及跳过功能。
广告页面组件设计
创建一个独立的广告组件,通常命名为SplashAd.vue:
<template>
<div class="splash-ad">
<img :src="adImage" alt="广告" />
<div class="skip-btn" @click="skipAd">
{{ countDown }}秒后跳过
</div>
</div>
</template>
<script>
export default {
data() {
return {
adImage: require('@/assets/ad.jpg'),
countDown: 5,
timer: null
}
},
mounted() {
this.startCountDown()
},
methods: {
startCountDown() {
this.timer = setInterval(() => {
if (this.countDown <= 1) {
this.$router.replace('/home')
}
this.countDown--
}, 1000)
},
skipAd() {
clearInterval(this.timer)
this.$router.replace('/home')
}
}
}
</script>
<style scoped>
.splash-ad {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
}
.skip-btn {
position: absolute;
right: 20px;
top: 20px;
padding: 5px 10px;
background: rgba(0,0,0,0.5);
color: white;
border-radius: 15px;
cursor: pointer;
}
</style>
路由配置与广告显示控制
在路由配置中设置广告页为初始页面,并通过路由守卫控制显示逻辑:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import SplashAd from './views/SplashAd.vue'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'splash',
component: SplashAd
},
{
path: '/home',
name: 'home',
component: Home
}
]
})
router.beforeEach((to, from, next) => {
const hasSeenAd = localStorage.getItem('hasSeenAd')
if (to.path === '/' && hasSeenAd) {
next('/home')
} else {
next()
}
})
export default router
广告显示频率控制
通过本地存储控制广告显示频率,避免每次打开都显示广告:
methods: {
skipAd() {
localStorage.setItem('hasSeenAd', 'true')
clearInterval(this.timer)
this.$router.replace('/home')
}
}
广告数据动态获取
实际项目中广告内容通常从后端API获取:
async mounted() {
try {
const response = await fetch('https://api.example.com/ads')
const data = await response.json()
this.adImage = data.imageUrl
this.startCountDown()
} catch (error) {
this.$router.replace('/home')
}
}
性能优化建议
广告图片预加载可以提升用户体验:
created() {
const img = new Image()
img.src = this.adImage
img.onload = () => {
this.imageLoaded = true
}
}
添加过渡效果使页面切换更平滑:
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}



