当前位置:首页 > VUE

vue swiper实现导航切换

2026-01-22 10:05:09VUE

安装 Swiper 依赖

在 Vue 项目中安装 Swiper 和 Vue-Awesome-Swiper:

npm install swiper vue-awesome-swiper

引入 Swiper 组件

在需要使用的组件中引入 Swiper 相关模块:

import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';

注册 Swiper 模块

在组件中注册 Navigation 模块并配置 Swiper:

vue swiper实现导航切换

export default {
  components: { Swiper, SwiperSlide },
  setup() {
    return {
      modules: [Navigation],
    };
  },
};

模板中使用 Swiper

在模板中添加 Swiper 容器和导航按钮:

<template>
  <swiper
    :modules="modules"
    :navigation="{
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    }"
  >
    <swiper-slide>Slide 1</swiper-slide>
    <swiper-slide>Slide 2</swiper-slide>
    <swiper-slide>Slide 3</swiper-slide>

    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </swiper>
</template>

自定义导航样式

添加 CSS 样式来自定义导航按钮的外观:

vue swiper实现导航切换

.swiper-button-prev,
.swiper-button-next {
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.swiper-button-prev:after,
.swiper-button-next:after {
  font-size: 20px;
}

响应式配置

根据需要添加响应式配置:

<swiper
  :breakpoints="{
    640: {
      slidesPerView: 2,
    },
    768: {
      slidesPerView: 3,
    },
  }"
>

动态内容处理

如果需要动态生成 slides,可以使用 v-for:

<swiper-slide v-for="(item, index) in items" :key="index">
  {{ item }}
</swiper-slide>

事件处理

可以添加事件监听来处理滑动动作:

<swiper @slideChange="onSlideChange">
methods: {
  onSlideChange(swiper) {
    console.log('当前索引:', swiper.activeIndex);
  }
}

标签: vueswiper
分享给朋友:

相关文章

vue实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…

vue watch实现

vue watch实现

在 Vue 中实现 watch 监听数据变化 Vue 的 watch 选项用于监听数据变化并执行相应的回调函数。以下是几种常见的实现方式: 基础用法 export default { data(…

vue指令实现

vue指令实现

Vue 指令的实现方式 Vue 指令是特殊的标记,用于在 DOM 元素上应用特定的行为。可以通过全局或局部方式注册自定义指令。 全局注册指令 在 Vue 应用中通过 Vue.directive 方法…

自己实现vue

自己实现vue

实现简易版 Vue.js 核心功能 要实现一个简易版 Vue.js,需要理解其核心功能:数据响应式、模板编译、依赖收集和虚拟 DOM。以下分模块实现关键功能。 数据响应式(Reactivity) 通…

vue  实现关联属性

vue 实现关联属性

Vue 实现关联属性 在 Vue 中实现关联属性通常涉及计算属性(computed properties)或侦听器(watchers),用于根据其他属性的变化动态更新目标属性。 使用计算属性 计算属…

vue实现数据删除

vue实现数据删除

vue实现数据删除的方法 使用v-for和v-on指令 在Vue中可以通过v-for指令渲染列表数据,结合v-on指令监听删除事件。定义一个方法处理删除逻辑,通常使用splice方法从数组中移除指定项…