重点1:setActiveItem 方法,手动切换幻灯片,需要切换的幻灯片的索引,从 0 开始;或相应
el-carousel-item的name属性值。
重点2:vue3中获取ref,需要先定义一个null接受,如本文中的
const carousel = ref(null);即可获取到。
重点3:vue3中如果想要响应式数据,需要用
ref或者reactive进行包裹。其中ref包裹的访问时需要加上.value而reactive包裹的无需加上.value。两者共同的区别就是在模板中使用的时候都不需要加.value即可访问。
<script setup>
import { ref } from 'vue'
const pageIndex = ref(0)
const carousel = ref(null);
const go = (index) => {
pageIndex.value = index
carousel.value.setActiveItem(index)
}
</script>
<template>
<el-row class="mb-4" style="background-color: #ccc;height: 50px;">
<el-button type="primary" @click="go(0)">Primary</el-button>
<el-button type="success" @click="go(1)">Success</el-button>
<el-button type="warning" @click="go(2)">Warning</el-button>
<el-button type="danger" @click="go(3)">Danger</el-button>
</el-row>
<div class="block text-center">
<el-carousel height="150px" :autoplay="false" ref="carousel">
<el-carousel-item>
<span>111</span>
</el-carousel-item>
<el-carousel-item>
<span>222</span>
</el-carousel-item>
<el-carousel-item>
<span>333</span>
</el-carousel-item>
<el-carousel-item>
<span>444</span>
</el-carousel-item>
</el-carousel>
</div>
</template>
<style scoped>
.demonstration {
color: var(--el-text-color-secondary);
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 150px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
</style>