0
点赞
收藏
分享

微信扫一扫

vue项目切换页面白屏不显示解决方案

追风骚年 2023-09-23 阅读 35

在Vue3中,可以使用组合API和ref来封装一个简单的轮播图组件。以下是一个基本的封装示例:

<template>
<div class="carousel">
<div v-for="item in items" :key="item.id" :style="{ backgroundImage: `url(${item.imageUrl})` }" :class="{ active: item.id === currentIndex }"></div>
</div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
props: {
dataList: {
type: Array,
default: () => []
},
interval: {
type: Number,
default: 3000
}
},
setup(props) {
const currentIndex = ref(0)
let timer = null

const items = props.dataList.map((item, index) => ({
...item,
id: index
}))

const stop = () => {
clearInterval(timer)
timer = null
}

const start = () => {
timer = setInterval(() => {
currentIndex.value = (currentIndex.value + 1) % items.length
}, props.interval)
}

onMounted(() => {
start()
})

onUnmounted(() => {
stop()
})

return {
items,
currentIndex
}
}
}
</script>

<style>
.carousel {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}

.carousel > div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-size: cover;
background-position: center center;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}

.carousel > div.active {
opacity: 1;
}
</style>

在模板中,使用v-for来遍历数据列表,并根据currentIndex来设置当前展示的轮播图。

在setup中,使用ref来定义currentIndex和timer变量。在onMounted和onUnmounted钩子中,分别启动和停止轮播循环。

最后在样式中,定义基本的轮播图样式。

举报

相关推荐

0 条评论