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

yizhihongxing

下面我将详细讲解"vue3+Pinia+TypeScript 实现封装轮播图组件"的完整攻略:

1. 前置知识

在开始之前需要先掌握以下知识:

  • Vue3基础语法
  • TypeScript基础语法
  • Pinia要点

2. 创建轮播图组件

  1. 创建组件文件

首先需要在项目中创建Carousel组件的.vue.ts文件,用于定义组件的模板和业务逻辑代码。

  1. 引入Pinia

在创建组件的.ts文件中引入Pinia:

import { defineComponent } from 'vue'
import { useStore } from 'pinia'
  1. 定义Carousel组件
import { defineComponent } from 'vue'
import { useStore } from 'pinia'

export default defineComponent({
  name: 'Carousel',
  props: ['items'],
  setup(props) {
    const store = useStore()

    // 内部业务逻辑代码

    return {}
  }
})

setup函数中,我们初始化了一个store实例,后续我们将使用它来管理轮播图数据。其中,props用于接收从父组件传递过来的props,这里我们接收了一个items数组,表示轮播图的图片列表。

  1. 添加轮播图数据State

接着,在创建Carousel.store.ts file文件中定义 Carousel组件的状态,如下所示:

import { defineStore } from 'pinia'

interface CarouselState {
  items: string[]
  currentIndex: number
  timer: null | number
}

export const useCarouselStore = defineStore({
  id: 'carousel',
  state: (): CarouselState => ({
    items: [],
    currentIndex: 0,
    timer: null
  })
})

在上面的代码中,我们使用了Pinia提供的defineStore函数定义了一个名为useCarouselStore的store实例,并定义了轮播图的状态,包括items(图片列表)、currentIndex(当前索引)和timer(轮播定时器)。

我们在这里也可以定义mutations, actions等来修改state中的属性

  1. 定义轮播图组件逻辑

结合上面创建的Carousel组件和useCarouselStore store实例,来实现轮播图组件的业务逻辑,代码如下:

import { defineComponent } from 'vue'
import { useStore } from 'pinia'
import { useCarouselStore } from './Carousel.store'

export default defineComponent({
  name: 'Carousel',
  props: ['items'],
  setup(props) {
    const carouselStore = useCarouselStore()
    const store = useStore()

    // 初始化轮播图数据
    carouselStore.items = props.items
    carouselStore.timer = setInterval(() => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex + 1) % carouselStore.items.length
    }, 3000)

    // 定义方法
    const goTo = (index: number) => {
      carouselStore.currentIndex = index
    }
    const prev = () => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex - 1 + carouselStore.items.length) %
        carouselStore.items.length
    }
    const next = () => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex + 1) % carouselStore.items.length
    }

    return { carouselStore, goTo, prev, next }
  }
})

在这里,在setup里面,我们初始化了store和轮播图的数据。我们还定义了一些函数用于处理轮播图的点击事件,比如goTo函数用于跳转到某个指定索引的图片、prev函数用于向前翻页、next函数用于向后翻页。

3. 应用轮播图组件到Vue页面

  1. 在Vue页面中引入Carousel组件。
<template>
  <div>
    <Carousel :items="items"></Carousel>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import Carousel from '@/components/Carousel.vue'

export default defineComponent({
  name: 'App',
  components: {
    Carousel
  },
  data() {
    return {
      items: [
        'https://picsum.photos/500/300',
        'https://picsum.photos/500/301',
        'https://picsum.photos/500/302',
        'https://picsum.photos/500/303'
      ]
    }
  }
})
</script>
  1. 在Vue页面中绑定数据到Carousel组件。
<template>
  <div>
    <Carousel :items="items"></Carousel>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import Carousel from '@/components/Carousel.vue'

export default defineComponent({
  name: 'App',
  components: {
    Carousel
  },
  data() {
    return {
      items: [
        'https://picsum.photos/500/300',
        'https://picsum.photos/500/301',
        'https://picsum.photos/500/302',
        'https://picsum.photos/500/303'
      ]
    }
  }
})
</script>

在这里,数据通过itemsprops传递到了Carousel组件中,且开始展示轮播图。

4. 示例说明

示例一

在轮播图组件中自定义前进/后退按钮,点击按钮可分别前进/后退一张图片。

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        <img
          v-if="currentIndex === index"
          :src="item"
          alt=""
          style="display:block;margin:0 auto;"
        />
      </li>
    </ul>
    <button @click="prev">prev</button>
    <button @click="next">next</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from 'pinia'
import { useCarouselStore } from './Carousel.store'

export default defineComponent({
  name: 'Carousel',
  props: ['items'],
  setup(props) {
    const carouselStore = useCarouselStore()
    const store = useStore()

    // 初始化轮播图数据
    carouselStore.items = props.items
    carouselStore.timer = setInterval(() => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex + 1) % carouselStore.items.length
    }, 3000)

    // 定义方法
    const goTo = (index: number) => {
      carouselStore.currentIndex = index
    }
    const prev = () => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex - 1 + carouselStore.items.length) %
        carouselStore.items.length
    }
    const next = () => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex + 1) % carouselStore.items.length
    }

    return { carouselStore, goTo, prev, next }
  }
})
</script>

示例二

对于轮播图组件,可以添加自动播放和暂停功能。

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        <img
          v-if="currentIndex === index"
          :src="item"
          alt=""
          style="display:block;margin:0 auto;"
        />
      </li>
    </ul>
    <button @click="prev">prev</button>
    <button @click="next">next</button>
    <button @click="stopTimer" v-if="isPlaying">pause</button>
    <button @click="startTimer" v-else>play</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from 'pinia'
import { useCarouselStore } from './Carousel.store'

export default defineComponent({
  name: 'Carousel',
  props: ['items'],
  setup(props) {
    const carouselStore = useCarouselStore()
    const store = useStore()

    // 初始化轮播图数据
    carouselStore.items = props.items
    carouselStore.timer = setInterval(() => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex + 1) % carouselStore.items.length
    }, 3000)

    // 定义方法
    const goTo = (index: number) => {
      carouselStore.currentIndex = index
    }
    const prev = () => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex - 1 + carouselStore.items.length) %
        carouselStore.items.length
    }
    const next = () => {
      carouselStore.currentIndex =
        (carouselStore.currentIndex + 1) % carouselStore.items.length
    }
    const startTimer = () => {
      carouselStore.timer = setInterval(() => {
        carouselStore.currentIndex =
          (carouselStore.currentIndex + 1) % carouselStore.items.length
      }, 3000)
    }
    const stopTimer = () => {
      clearInterval(carouselStore.timer)
      carouselStore.timer = null
    }

    return { carouselStore, goTo, prev, next, startTimer, stopTimer, isPlaying }
  },
  computed: {
    isPlaying() {
      return this.carouselStore.timer !== null
    }
  }
})
</script>

在这里,我们添加了自动播放和暂停功能,当点击暂停按钮时,清除定时器,点击播放按钮时重新设置定时器,达到轮播效果。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue3+Pinia+TypeScript 实现封装轮播图组件 - Python技术站

(0)
上一篇 2023年6月25日
下一篇 2023年6月25日

相关文章

  • hash值破解工具(findmyhash与hash-identifier破解hash值)

    hash值破解工具(findmyhash与hash-identifier破解hash值) 哈希值是一种加密技术,用于将任意长度的数据转换为固定长度的数据。哈希值通常于验证数据的完整性和安全性。在本攻略中,我们将介两个常用的哈希值破解工具:findhash 和 hash-identifier,并提供两个示例说明。 findmyhash findmyhash 是…

    other 2023年5月6日
    00
  • uniapp导入导出excel

    uniapp导入导出excel攻略 在uniapp中,可以使用js-xlsx库实现导入导出excel。以下是详细的攻略: 步骤 以下是导入导出excel的步骤: 安装-xlsx库。 在uniapp项目中,使用npm安装js-xlsx库。 bash npm install xlsx –save 导入excel文件。 在uniapp中,可以使用uni.choo…

    other 2023年5月7日
    00
  • JS中构造函数的基本特性与优缺点

    JavaScript中的构造函数是用于创建对象的函数。在JavaScript中,你可以通过两种方式创建对象: 字面量创建对象,例如: let obj = { name: ‘John’, age: 25, greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} yea…

    other 2023年6月26日
    00
  • 电脑桌面右键新建菜单中没有Word/Excel/PPT等文档怎么办?

    若电脑桌面右键新建菜单中没有Word/Excel/PPT等文档,可能是由于Office软件未正常安装或被卸载导致相关菜单项丢失。 解决方法如下: 步骤一:检查Office软件是否正常安装 首先,需要确认电脑已安装Office软件且安装是完整的。可以通过以下操作来确认: 点击Windows开始按钮,并在搜索框中输入“控制面板”。 在弹出的控制面板窗口中,选择“…

    other 2023年6月27日
    00
  • 详解Qt使用QImage类实现图像基本操作

    详解Qt使用QImage类实现图像基本操作攻略 1. 前言 在Qt中,我们可以使用QImage类来实现图像基本操作,如加载、保存、绘制以及一些简单的处理。本篇攻略将详细讲解QImage类的使用方法。 2. QImage的加载与保存 QImage类提供了多种加载和保存图像的方法,下面介绍两种常用的方法。 2.1 加载图像 使用QImage::load()方法可…

    other 2023年6月26日
    00
  • python判定为空

    Python判定为空 在Python编程中,经常会遇到需要判断一个变量是否为空的情况。常见的空值包括None、空字符串、空列表、空字典、空元组等。本文将介绍在Python中判断各种空值的方法。 判断None 在Python中,用关键字None表示空值。当一个变量的值为None时,可以使用is或is not来判断。例如: a = None if a is No…

    其他 2023年3月28日
    00
  • python实现去除下载电影和电视剧文件名中的多余字符的方法

    好的。实现去除下载电影和电视剧文件名中的多余字符有几种方法,本攻略介绍使用Python进行字符串操作来实现。 1. 准备工作 在开始编写代码之前,先了解几个在字符串处理中经常使用到的Python类库: re:Python自带的正则表达式类库,用于匹配和替换字符串中的模式。 os:Python中的系统类库,用于获取、修改文件的路径和名称。 2. 去除下载电影或…

    other 2023年6月27日
    00
  • Android时间选择器、日期选择器实现代码

    Sure! Here is a detailed guide on implementing the code for Android time picker and date picker. I will provide two examples to illustrate the process. Time Picker Implementation T…

    other 2023年9月6日
    00
合作推广
合作推广
分享本页
返回顶部