0
点赞
收藏
分享

微信扫一扫

uniapp 轮播图(含组件封装,自动注册全局组件)


效果预览

uniapp 轮播图(含组件封装,自动注册全局组件)_ci

组件封装

src\components\SUI_Swiper.vue

可参考官网配置更多属性

  • swiper
  • navigator

<script setup lang="ts">
import { ref } from 'vue'
defineProps({
  config: Object,
})

const activeIndex = ref(0)
const change: UniHelper.SwiperOnChange = (e) => {
  activeIndex.value = e.detail.current
}
</script>

<template>
  <view class="carousel">
    <swiper
      @change="change"
      :circular="config?.circular || true"
      :autoplay="config?.autoplay || false"
      :interval="config?.interval || 3000"
    >
      <swiper-item v-for="(item, index) in config?.itemList" :key="index">
        <navigator
          :url="item.url"
          :open-type="item.openType || 'navigate'"
          hover-class="none"
          class="navigator"
        >
          <image mode="aspectFill" class="image" :src="item.src"></image>
        </navigator>
      </swiper-item>
    </swiper>
    <!-- 指示点 -->
    <view class="indicator">
      <text
        v-for="(item, index) in config?.itemList"
        :key="item"
        class="dot"
        :class="{ active: index === activeIndex }"
      ></text>
    </view>
  </view>
</template>

<style lang="scss">
/* 轮播图 */
.carousel {
  height: 280rpx;
  position: relative;
  overflow: hidden;
  transform: translateY(0);
  background-color: #efefef;
  .indicator {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 16rpx;
    display: flex;
    justify-content: center;
    .dot {
      width: 30rpx;
      height: 6rpx;
      margin: 0 8rpx;
      border-radius: 6rpx;
      background-color: rgba(255, 255, 255, 0.4);
    }
    .active {
      background-color: #fff;
    }
  }
  .navigator,
  .image {
    width: 100%;
    height: 100%;
  }
}
</style>

自动注册全局组件

在 src\pages.json 中添加

// 自动导入src/components 目录中以 SUI_开头的组件
      "^SUI_(.*)": "@/components/SUI_$1.vue"

完整范例代码如下:
src\pages.json

// 组件自动导入
  "easycom": {
    "autoscan": true,
    "custom": {
      // uni-ui 规则如下配置
      "^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue",
      // 自动导入src/components 目录中以 SUI_开头的组件
      "^SUI_(.*)": "@/components/SUI_$1.vue"
    }
  },

使用组件

<SUI_Swiper :config="swiperConfig" />

const swiperConfig = {
  autoplay: true,
  interval: 3000,
  itemList: [
    {
      // 跳转到页面 '/pages/login/login'
      url: '/pages/login/login',
      src: 'https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/uploads/slider_1.jpg',
    },
    {
      // 跳转到tab页签 '/pages/my/my'
      openType: 'switchTab',
      url: '/pages/my/my',
      src: 'https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/uploads/slider_2.jpg',
    },
  ],
}


举报

相关推荐

0 条评论