请把上述代码改写成Vue3的Option式编程模式代码
时间: 2024-10-01 20:09:31 浏览: 28
在Vue3的Composition API中,我们通常会使用`setup()`函数来组织业务逻辑,而不是传统的`methods`。以下是将上述模板和脚本转换为Option式编程模式的示例:
```html
<template>
<div id="swiper-container">
<swiper :options="swiperOptions" @change="handleSlideChange">
<swiper-slide v-for="(tab, index) in tabs" :key="index">
{{ tab.content }}
</swiper-slide>
<div class="swiper-button-next" @click="prevSlide"></div>
<div class="swiper-button-prev" @click="nextSlide"></div>
</swiper>
</div>
</template>
<script>
import { onMounted, Ref, watchEffect } from 'vue'
export default {
name: 'SwiperComponent',
setup(props, context) {
const swiperRef = Ref(null);
const tabs = [
{ content: 'Tab 1' },
{ content: 'Tab 2' },
{ content: 'Tab 3' },
];
const swiperOptions = {
// ... 填写Swiper初始化配置
};
function handleSlideChange() {
const currentIndex = swiperRef.value.realIndex;
tabs.forEach((tab, index) => {
tab.isActive = (index === currentIndex);
});
}
onMounted(() => {
const swiper = new Swiper(swiperRef.value.$el, swiperOptions);
watchEffect(() => {
// 当tabs变化时,更新Swiper滑动位置
if (swiper) {
const tabIndex = tabs.findIndex(tab => tab.isActive);
if (tabIndex !== -1) {
swiper.slideTo(tabIndex);
}
}
});
context.emit('mounted', swiper); // 如果需要的话,可以在此处向外部组件传递Swiper实例
});
const prevSlide = () => {
if (swiperRef.value.previousIndex !== undefined && swiperRef.value.previousIndex !== -1) {
handleSlideChange();
}
};
const nextSlide = () => {
if (swiperRef.value.currentIndex !== swiperRef.value.slides.length - 1) {
handleSlideChange();
}
};
return {
swiperRef,
prevSlide,
nextSlide,
};
},
};
</script>
<style scoped>
.swiper-button-next,
.swiper-button-prev {
/* 样式省略 */
}
</style>
```
这里使用了`Ref`来创建Swiper的引用,并在`setup`函数中初始化Swiper,同时通过`watchEffect`监听tabs的变化来同步Swiper的状态。
阅读全文