• Vue3项目关于轮播图的封装应该怎么封装才是最简单的呢


    Vue3中,可以使用组合API和ref来封装一个简单的轮播图组件。以下是一个基本的封装示例:

    1. <template>
    2. <div class="carousel">
    3. <div v-for="item in items" :key="item.id" :style="{ backgroundImage: `url(${item.imageUrl})` }" :class="{ active: item.id === currentIndex }"></div>
    4. </div>
    5. </template>
    6. <script>
    7. import { ref, onMounted, onUnmounted } from 'vue'
    8. export default {
    9. props: {
    10. dataList: {
    11. type: Array,
    12. default: () => []
    13. },
    14. interval: {
    15. type: Number,
    16. default: 3000
    17. }
    18. },
    19. setup(props) {
    20. const currentIndex = ref(0)
    21. let timer = null
    22. const items = props.dataList.map((item, index) => ({
    23. ...item,
    24. id: index
    25. }))
    26. const stop = () => {
    27. clearInterval(timer)
    28. timer = null
    29. }
    30. const start = () => {
    31. timer = setInterval(() => {
    32. currentIndex.value = (currentIndex.value + 1) % items.length
    33. }, props.interval)
    34. }
    35. onMounted(() => {
    36. start()
    37. })
    38. onUnmounted(() => {
    39. stop()
    40. })
    41. return {
    42. items,
    43. currentIndex
    44. }
    45. }
    46. }
    47. </script>
    48. <style>
    49. .carousel {
    50. position: relative;
    51. width: 100%;
    52. height: 100%;
    53. overflow: hidden;
    54. }
    55. .carousel > div {
    56. position: absolute;
    57. top: 0;
    58. left: 0;
    59. width: 100%;
    60. height: 100%;
    61. background-size: cover;
    62. background-position: center center;
    63. opacity: 0;
    64. transition: opacity 0.5s ease-in-out;
    65. }
    66. .carousel > div.active {
    67. opacity: 1;
    68. }
    69. </style>

    在模板中,使用v-for来遍历数据列表,并根据currentIndex来设置当前展示的轮播图。

    在setup中,使用ref来定义currentIndex和timer变量。在onMounted和onUnmounted钩子中,分别启动和停止轮播循环。

    最后在样式中,定义基本的轮播图样式。

  • 相关阅读:
    模板 树状数组套主席树查询动态区间k小,区间修改版
    软考系统架构师倒计时第1天
    Good idea of English learning
    面试题--基础篇
    事务管理需要了解的前置知识
    自学Python第二十六天- Tornado 框架
    Java Word文档发送给外部文件上传API
    AI 自动写代码插件 Copilot(副驾驶员)
    WEB渗透之SQL 注入
    Vue3:组件的生命周期函数
  • 原文地址:https://blog.csdn.net/qq_70036866/article/details/133165142