vue实现广告横幅

Vue实现广告横幅的方法
使用v-if/v-show控制显示
<template>
<div v-if="showBanner" class="ad-banner">
<span @click="closeBanner">×</span>
<img src="@/assets/ad.jpg" alt="广告">
</div>
</template>
<script>
export default {
data() {
return {
showBanner: true
}
},
methods: {
closeBanner() {
this.showBanner = false
}
}
}
</script>
<style scoped>
.ad-banner {
position: fixed;
bottom: 0;
width: 100%;
height: 80px;
background: #f5f5f5;
text-align: center;
}
.ad-banner span {
position: absolute;
right: 10px;
top: 5px;
cursor: pointer;
}
</style>
轮播广告实现
<template>
<div class="carousel">
<div v-for="(ad, index) in ads"
:key="index"
v-show="currentIndex === index">
<img :src="ad.image" :alt="ad.title">
</div>
<button @click="prev">上一张</button>
<button @click="next">下一张</button>
</div>
</template>
<script>
export default {
data() {
return {
ads: [
{ image: '@/assets/ad1.jpg', title: '广告1' },
{ image: '@/assets/ad2.jpg', title: '广告2' },
{ image: '@/assets/ad3.jpg', title: '广告3' }
],
currentIndex: 0,
timer: null
}
},
mounted() {
this.startAutoPlay()
},
methods: {
startAutoPlay() {
this.timer = setInterval(() => {
this.next()
}, 3000)
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.ads.length) % this.ads.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.ads.length
}
}
}
</script>
使用第三方组件
安装vue-awesome-swiper:

npm install swiper vue-awesome-swiper
实现代码:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(ad, index) in ads" :key="index">
<img :src="ad.image" :alt="ad.title">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
ads: [
{ image: '@/assets/ad1.jpg', title: '广告1' },
{ image: '@/assets/ad2.jpg', title: '广告2' },
{ image: '@/assets/ad3.jpg', title: '广告3' }
],
swiperOptions: {
pagination: {
el: '.swiper-pagination'
},
autoplay: {
delay: 3000,
disableOnInteraction: false
},
loop: true
}
}
}
}
</script>
响应式广告实现
<template>
<div class="responsive-ad">
<img v-if="isMobile" src="@/assets/ad-mobile.jpg" alt="移动端广告">
<img v-else src="@/assets/ad-desktop.jpg" alt="桌面端广告">
</div>
</template>
<script>
export default {
data() {
return {
isMobile: false
}
},
mounted() {
this.checkScreenSize()
window.addEventListener('resize', this.checkScreenSize)
},
beforeDestroy() {
window.removeEventListener('resize', this.checkScreenSize)
},
methods: {
checkScreenSize() {
this.isMobile = window.innerWidth < 768
}
}
}
</script>






