vue3+Pinia+TypeScript 实现封装轮播图组件

目录
  • 为什么封装?
  • 静态结构 后面再进行更改
  • 请求数据都存放在pinia里面
  • 类型检测
  • 页面级组件
  • 全局组件

为什么封装?

  • 迎合es6模块化开发思想
  • 注册为全局组件,可以更好地复用,需要用到的地方,直接使用标签即可

静态结构 后面再进行更改

<script lang="ts" setup name="XtxCarousel">
defineProps()
</script>
<template>
  <div class="xtx-carousel">
    <ul class="carousel-body">
      <li class="carousel-item fade">
        <RouterLink to="/">
          <img
            src="http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-04-15/1ba86bcc-ae71-42a3-bc3e-37b662f7f07e.jpg"
            alt=""
          />
        </RouterLink>
      </li>
      <li class="carousel-item">
        <RouterLink to="/">
          <img
            src="http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-04-15/1ba86bcc-ae71-42a3-bc3e-37b662f7f07e.jpg"
            alt=""
          />
        </RouterLink>
      </li>
      <li class="carousel-item">
        <RouterLink to="/">
          <img
            src="http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-04-15/1ba86bcc-ae71-42a3-bc3e-37b662f7f07e.jpg"
            alt=""
          />
        </RouterLink>
      </li>
    </ul>
    <a href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  class="carousel-btn prev"
      ><i class="iconfont icon-angle-left"></i
    ></a>
    <a href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  class="carousel-btn next"
      ><i class="iconfont icon-angle-right"></i
    ></a>
    <div class="carousel-indicator">
      <span class="active"></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-carousel {
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 150px;
  position: relative;
  .carousel {
    &-body {
      width: 100%;
      height: 100%;
    }
    &-item {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      transition: opacity 0.5s linear;
      &.fade {
        opacity: 1;
        z-index: 1;
      }
      img {
        width: 100%;
        height: 100%;
      }
    }
    &-indicator {
      position: absolute;
      left: 0;
      bottom: 20px;
      z-index: 2;
      width: 100%;
      text-align: center;
      span {
        display: inline-block;
        width: 12px;
        height: 12px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 50%;
        cursor: pointer;
        ~ span {
          margin-left: 12px;
        }
        &.active {
          background: #fff;
        }
      }
    }
    &-btn {
      width: 44px;
      height: 44px;
      background: rgba(0, 0, 0, 0.2);
      color: #fff;
      border-radius: 50%;
      position: absolute;
      top: 228px;
      z-index: 2;
      text-align: center;
      line-height: 44px;
      opacity: 0;
      transition: all 0.5s;
      &.prev {
        left: 20px;
      }
      &.next {
        right: 20px;
      }
    }
  }
  &:hover {
    .carousel-btn {
      opacity: 1;
    }
  }
}
</style>

请求数据都存放在pinia里面

import { defineStore } from 'pinia'
import request from '@/utils/request'
import { BannerItem, IApiRes } from '@/types/data'

export default defineStore('home', {
  persist: {
    enabled: true
  },

  state() {
    return {
      bannerList: [] as BannerItem[]
    }
  },
  actions: {
    // 拿轮播图数据
    async getBannerList() {
      const res = await request.get<IApiRes<BannerItem[]>>('/home/banner')
      console.log('拿轮播图数据', res)
      this.bannerList = res.data.result
    }
  }
})

类型检测

// 所有的接口的通用类型
export interface IApiRes<T> {
  msg: string,
  result: T
}

// 轮播图数据中的项
export type BannerItem = {
  id: string;
  imgUrl: string;
  hrefUrl: string;
  type: string;
}

页面级组件

<script lang="ts" setup>
import useStore from '@/store';
const { home } = useStore()
// 发请求
home.getBannerList()

</script>
<template>
  <div class="home-banner">
    <!-- 轮播图子组件 -->
    <XtxCarousel :slides="home.bannerList" :autoPlay="true" :duration="1000"/>
  </div>
</template>

<style scoped lang="less">
.home-banner {
  width: 1240px;
  height: 450px;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 98;
  background-color: #ccc;
}
/deep/ .xtx-carousel .carousel-btn.prev {
  left: 270px !important;
}
/deep/ .xtx-carousel .carousel-indicator {
  padding-left: 250px;
}
</style>

全局组件

<script lang="ts" setup name="XtxCarousel">
import { BannerItem } from '@/types/data'
import { onBeforeUnmount, onMounted, ref } from 'vue';
// 定义props
const { slides, autoPlay, duration } = defineProps<{
  slides: BannerItem[],
  autoPlay?: boolean, // 是否开启自动播放
  duration?: number // 自动播放的间隔时间
}>()

// 当前哪个图片选中 高亮
const active = ref(1)

// 点击右侧箭头++
const hNext = () => {
  active.value++
  if(active.value === slides.length){
    active.value = 0
  }
}

// 点击左侧箭头--
const hPrev = () => {
  active.value--
  if(active.value < 0){
    active.value = slides.length - 1
  }
}

// 如果开启了自动播放,则每隔duration去播放下一张: hNext()
onMounted(() => {
  start()
})

onBeforeUnmount(() => {
  stop()
})

let timer = -1

// 鼠标离开要继续播放
const start = () => {
  if(autoPlay) {
    timer = window.setInterval(() => {
      hNext()
    }, duration)
  }
}

// 鼠标hover要暂停播放
const stop = () => {
  clearInterval(timer)
}
</script>

<template>
  <div class="xtx-carousel" @mouseleave="start()" @mouseenter="stop()">
    <ul class="carousel-body">
      <li class="carousel-item"
      :class="{ fade: idx === active}"
      v-for="(it, idx) in slides" :key="it.id">
        <RouterLink to="/">
          <img :src="it.imgUrl" alt="" />
        </RouterLink>
      </li>
    </ul>
    <a @click="hPrev" href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  class="carousel-btn prev"><i class="iconfont icon-angle-left"></i></a>
    <a @click="hNext" href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  class="carousel-btn next"><i class="iconfont icon-angle-right"></i></a>
    <div class="carousel-indicator">
      <span
      v-for="(it, idx) in slides"
      :class="{ active: active===idx}"
      @mouseenter="active = idx"
      ></span>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-carousel {
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 150px;
  position: relative;
  .carousel {
    &-body {
      width: 100%;
      height: 100%;
    }
    &-item {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0; // 不可见
      transition: opacity 0.5s linear;
      &.fade {
        opacity: 1; // 可见
        z-index: 1;
      }
      img {
        width: 100%;
        height: 100%;
      }
    }
    &-indicator {
      position: absolute;
      left: 0;
      bottom: 20px;
      z-index: 2;
      width: 100%;
      text-align: center;
      span {
        display: inline-block;
        width: 12px;
        height: 12px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 50%;
        cursor: pointer;
        ~ span {
          margin-left: 12px;
        }
        &.active {
          background: #fff;
        }
      }
    }
    &-btn {
      width: 44px;
      height: 44px;
      background: rgba(0, 0, 0, 0.2);
      color: #fff;
      border-radius: 50%;
      position: absolute;
      top: 228px;
      z-index: 2;
      text-align: center;
      line-height: 44px;
      opacity: 0;
      transition: all 0.5s;
      &.prev {
        left: 20px;
      }
      &.next {
        right: 20px;
      }
    }
  }
  &:hover {
    .carousel-btn {
      opacity: 1;
    }
  }
}
</style>

到此这篇关于vue3+Pinia+TypeScript 实现封装轮播图组件的文章就介绍到这了,更多相关vue3 封装轮播图内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Vue3 TypeScript 实现useRequest详情

    目录 前言: 效果展示 Axios interface axios的简单封装 useRequest 如何使用 添加泛型支持 queryKey的问题 完整代码 结语 前言: 自从 Vue3 更新之后,算是投入了比较大的精力写了一个较为完善的Vue3.2 + Vite2 + Pinia + Naive UI的B端模版,在做到网络请求这一块的时候,最初使用的是VueRequest的useRequest,但是因为VueRequest的useRequest的cancel关闭请求并不是真正的关闭,对我个人来

  • Vue+TypeScript中处理computed方式

    目录 什么是 「computed」 「computed」 的用途 在TypeScript怎么用 另一种方案 vue computed正确使用方式 computed or methods computed or watch 什么是 「computed」 「computed」 是Vue中提供的一个计算属性.它被混入到Vue实例中,所有的getter和setter的this上下文自动的绑定为Vue实例.计算属性的结果会被缓存,除非依赖的响应式property变化才会从新计算. 「computed」 的

  • vue项目中使用ts(typescript)入门教程

    目录 1.引入Typescript 2.配置文件webpack配置 3.让项目识别.ts 4.vue组件的编写 data()中定义数据 props传值 完整代码案例 最近项目需要将原vue项目结合ts的使用进行改造,这个后面应该是中大型项目的发展趋势,看到一篇不错的入门教程,结合它并进行了一点拓展记录之.本文从安装到vue组件编写进行了说明,适合入门. 1.引入Typescript npm install vue-class-component vue-property-decorator --

  • TypeScript在Vuex4中使用TS实战分享

    目录 简介 createStore GetterTree MutationTree ActionTree ModuleTree 实战 整体目录结构 首先定义根state的类型 在创建store的时候将根state的类型传递进去. 并且需要导出key 在Vue实例使用store的时候将key一并传入. 在vue组件使用 自定义useStore()方法 modules的使用 总结 简介 虽然TypeScript知识点学了很多,但是在实际项目中很多小伙伴还并不知道怎么用,今天笔者结合Vuex4来使用T

  • Vue3中使用typescript封装axios的实例详解

    这个axios封装,因为是用在vue3的demo里面的,为了方便,在vue3的配置里面按需加载element-plus 封装axios http.ts import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios' import { IResponseData } from '@/types' import { ElMessage, ElLoading, ILoadingInstance

  • TypeScript Pinia实战分享(Vuex和Pinia对比梳理总结)

    目录 简介 安装 创建pinia并传递给vue实例 创建store state getters actions 在vue组件使用 获取state 获取getters 修改state 数据持久化 总结 简介 今天我们再来实战下官方推荐的新的vue状态管理工具Pinia. pinia 由 vue 团队中成员所开发的,因此也被认为是下一代的 vuex,即 vuex5.x,在 vue3 的项目中使用也是备受推崇.所以 pinia 的学习迫在眉睫. 下面我们正式开始pinia的学习吧. 安装 yarn a

  • vue3+Pinia+TypeScript 实现封装轮播图组件

    目录 为什么封装? 静态结构 后面再进行更改 请求数据都存放在pinia里面 类型检测 页面级组件 全局组件 为什么封装? 迎合es6模块化开发思想 注册为全局组件,可以更好地复用,需要用到的地方,直接使用标签即可 静态结构 后面再进行更改 <script lang="ts" setup name="XtxCarousel"> defineProps() </script> <template> <div class=&qu

  • vue3.0封装轮播图组件的步骤

    接着上一篇文章,熟悉vue3.0的基本用法,和使用一段时间以后,开始准备开发适用于vue3.0使用的pc端的组件库.会陆续跟新一些组件库的写法和注意事项,有兴趣的同学可以多多关注哦,不多bb,开始. 开发一个轮播图组件,适用pc端,(暂无考虑app), 使用于vue3.0 + TS 大致的实现效果是这样: 图片自由轮播,对应圆点图片跳转,左右指示器跳转等.暴露以下options配置: 以上是主要的options,下面展开来说一下具体如何封装. 一:封装思想 在vue3.0和vue2.0中封装组件

  • vue3封装轮播图组件的方法

    目的 封装轮播图组件,直接使用,具体内容如下 大致步骤 准备my-carousel组件基础布局,全局注册 准备home-banner组件,使用my-carousel组件,再首页注册使用. 深度作用选择器覆盖my-carousel组件的默认样式 在home-banner组件获取轮播图数据,传递给my-carousel组件 在my-carousel组件完成渲染 自动播放,暴露自动轮播属性,设置了就自动轮播 如果有自动播放,鼠标进入离开,暂停,开启 指示器切换,上一张,下一张 销毁组件,清理定时器 落

  • Vue使用Swiper封装轮播图组件的方法详解

    目录 Swiper 为什么要封装组件 开始封装 1.下载安装Swiper 2.引入css样式文件 3.引入js文件 4.把官网使用方法中的HTML结构复制粘贴过来 5.初始化Swiper 自定义效果 完整代码 效果展示 Swiper Swiper是一个很常用的用于实现各种滑动效果的插件,PC端和移动端都能很好的适配. 官网地址:www.swiper.com.cn/ 目前最新版本是Swiper7,但众所周知最新版本通常不稳定,所以这里使用Swiper6来封装. Swiper各版本区别: 为什么要封

  • JavaScript实现原型封装轮播图

    本文实例为大家分享了JavaScript实现原型封装轮播图的具体代码,供大家参考,具体内容如下 只要用dom元素调用这个方法,传一个数组进去,里面放的是图片的路径. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-wid

  • UGUI轮播图组件实现方法详解

    本文实例为大家分享了UGUI轮播图组件实现的具体代码,供大家参考,具体内容如下 要用到,于是就自已做了一个,自认为封装上还是OK的,开发于unity5.1.2. 支持自动轮播.手势切换.代码调用切换,支持水平和竖直两个方向以及正负方向轮播,轮播索引改变有回调可以用,也可以获取到当前处于正中的子元素. 要注意的是,向轮播列表中加入新元素不能直接setparent,要调用该组件的AddChild方法 下面是鄙人的代码: /// 主要关注属性.事件及函数: /// public int Current

  • 轮播图组件js代码

    本文实例为大家分享了JavaScript轮播图组件代码,供大家参考,具体内容如下 //轮播图组件 function Rolling(o) { this.index = ++o.index || 1; //当前滚动的位置,当index大于可轮播的次数listLength或者等于0,为不可滚动状态 this.num = o.num || 1; //默认滚动一个列表 this.obj = o.obj || null; //要轮播的对象ul this.perObj = o.perObj || null;

  • Vue的轮播图组件实现方法

    今天在上慕课老师fishenal的vue实战课程的时候,有一个轮播图组件实现,在跟着做的时候,自己也踩了一些坑.此外,在原课程案例的基础上,我加入了不同方向的滑动功能. 本文章采用Vue结合Css3来实现轮播图. 首先要了解的是Vue的动画原理.在vue中,如果我们要给元素设置动画效果,则需要使用一个<transition name="targetClassName"></transition>将相应的元素包裹住,如下: <transition name=

  • Vue中使用better-scroll实现轮播图组件

    better-scroll 是什么 better-scroll 是一款重点解决移动端(已支持 PC)各种滚动场景需求的插件.它的核心是借鉴的 iscroll 的实现,它的 API 设计基本兼容 iscroll,在 iscroll 的基础上又扩展了一些 feature 以及做了一些性能优化. better-scroll 是基于原生 JS 实现的,不依赖任何框架.它编译后的代码大小是 63kb,压缩后是 35kb,gzip 后仅有 9kb,是一款非常轻量的 JS lib. 今天我们利用它实现一个横向

  • android轮播图组件的制作方法

    本文实例为大家分享了android轮播图组件的制作方法,供大家参考,具体内容如下 BannerLayout package com.coral3.common_module.components; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.LayoutInfla

随机推荐