<template>
  <el-carousel :interval="4000" type="card" height="200px">
    <el-carousel-item v-for="item in 6" :key="item">
      <img :src="getImageUrl(item)" alt="Carousel Item" />
    </el-carousel-item>
  </el-carousel>
</template>
<script>
import { ref } from 'vue';

export default {
  setup() {
    // 定义一个包含图片 URL 的数组
    const images = [
      '/path/to/image1.jpg',
      '/path/to/image2.jpg',
      '/path/to/image3.jpg',
      '/path/to/image4.jpg',
      '/path/to/image5.jpg',
      '/path/to/image6.jpg',
    ];

    // 创建一个引用,用于存储当前图片的索引
    const currentIndex = ref(0);

    // 获取指定索引的图片 URL 的函数
    const getImageUrl = (index) => {
      return images[index];
    };

    return {
      currentIndex,
      getImageUrl,
    };
  },
};
</script>
<style scoped>
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  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>
<p>在上面的示例中,我们从 Vue 组合式 API 中导入了 <code>ref</code> 函数,并使用它创建了一个响应式引用,用于存储当前图片的索引。我们还定义了一个包含图片 URL 的数组和一个 <code>getImageUrl</code> 函数,该函数返回指定索引的图片 URL。</p>
<p>在模板中,我们使用 <code>v-for</code> 指令遍历 <code>images</code> 数组,并在每个 <code>el-carousel-item</code> 组件中显示每个图片。我们将 <code>img</code> 元素的 <code>src</code> 属性绑定到 <code>getImageUrl</code> 函数,并传递当前项目的索引。</p>
<p>请确保将 <code>/path/to/imageX.jpg</code> URL 替换为实际静态图片的路径。</p>
Element Plus 轮播图组件:使用 Vue 3 组合式 API 访问静态资源

原文地址: https://www.cveoy.top/t/topic/qzhE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录