要让element plus组件可以访问静态资源并实现轮播,可以使用组合式API的方式来实现。首先,需要在项目中创建一个components文件夹,然后在其中创建一个Carousel.vue组件文件。

Carousel.vue组件中,可以使用defineComponent函数来定义组件,并导入refonMounted函数。然后,可以在setup函数中使用ref来创建一个响应式的变量images,用来存储要轮播的图片路径数组。可以将图片路径数组作为props传入组件。

接下来,在onMounted钩子函数中,可以使用import()函数动态导入图片资源,并将导入的图片路径添加到images数组中。

最后,在模板中使用el-carousel组件,并使用v-for指令遍历images数组,在每个el-carousel-item中使用img标签来展示图片。

以下是修改后的Carousel.vue组件的代码示例:

<template>
  <el-carousel :interval="4000" type="card" height="400px">
    <el-carousel-item v-for="item in images" :key="item">
      <img :src="item" alt="" />
    </el-carousel-item>
  </el-carousel>
</template>

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

export default defineComponent({
  props: {
    images: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const images = ref([]);

    onMounted(async () => {
      const importImages = async () => {
        const imagePaths = props.images;
        const importedImages = [];

        for (const imagePath of imagePaths) {
          const { default: image } = await import(`@/assets/${imagePath}`);
          importedImages.push(image);
        }

        images.value = importedImages;
      };

      await importImages();
    });

    return {
      images,
    };
  },
});
</script>

然后,在需要使用轮播组件的页面中,可以导入并使用Carousel组件,并将要轮播的图片路径数组作为images属性传入。

<template>
  <div>
    <carousel :images="carouselImages" />
    <img src="../../assets/img1/img_2.png" alt="" />
    <img src="../../assets/img1/img_3.png" alt="" />
  </div>
</template>

<script>
import Carousel from '@/components/Carousel.vue';

export default {
  components: {
    Carousel,
  },
  data() {
    return {
      carouselImages: ['img1/img_1.png', 'img1/img_2.png', 'img1/img_3.png'],
    };
  },
};
</script>

这样就能实现访问静态资源并实现轮播的效果了,而不使用require函数

el-carousel interval=4000 type=card height=400px el-carousel-item v-for=item in 6 key=item img src=assetsimg1img_1png alt= el-carousel-item el-carouselimg src=asse

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

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