当前位置: 首页 > 工具软件 > Per.js > 使用案例 >

关于Vue使用swiper.js的那些事

广晔
2023-12-01

Swiper中文网-轮播图幻灯片js插件,H5页面前端开发

以上是官网.

GitHub - surmon-china/vue-awesome-swiper:  Swiper component for @vuejsy​​​​​​​y

以上是 github 示例

关于swiper , vue2 和 vue 3 的使用上, 是不一样的

  • vue 3
    • vue3 可以直接按照官网例子. 直接使用
//  全局安装 npm i swiper

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="onSwiper"
    @slideChange="onSlideChange"
  >
    <swiper-slide>Slide 1</swiper-slide>
    <swiper-slide>Slide 2</swiper-slide>
    <swiper-slide>Slide 3</swiper-slide>
    ...
  </swiper>
</template>
<script>
  // Import Swiper Vue.js components
  import { Swiper, SwiperSlide } from 'swiper/vue';

  // Import Swiper styles
  import 'swiper/css';

  export default {
    components: {
      Swiper,
      SwiperSlide,
    },
    setup() {
      const onSwiper = (swiper) => {
        console.log(swiper);
      };
      const onSlideChange = () => {
        console.log('slide change');
      };
      return {
        onSwiper,
        onSlideChange,
      };
    },
  };
</script>
  • vue 2
    • vue2 需要使用到  vue-awesome-swiper 
    • 官方说 css 引用 是  swiper/css/swiper.css , 我实际使用的时候, 却找不到文件, 需要改为swiper/dist/css/swiper.css
// 安装包 cnpm install swiper vue-awesome-swiper --save

<template>
  <div class="swiper-box">
    <swiper
      ref="mySwiper"
      :options="swiperOption"
      @swiper="onSwiper"
      @slideChange="onSlideChange"
    >
      <swiper-slide
        v-for="item in 5"
        :key="item"
      >Slide {{item}}</swiper-slide>
    </swiper>
  </div>
</template>

<script>
import { Swiper, SwiperSlide, directive } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
export default {
  name: "self-swiper",
  components: {
    Swiper,
    SwiperSlide,
  },
  data () {
    return {
      swiperOption: {
        autoplay: false,
        slidesPerView: 5,
        spaceBetween: 14,
      }
    }
  },
  directives: {
    swiper: directive
  },
  computed: {
    swiper () {
      return this.$refs.mySwiper.$swiper
    }
  },
  mounted () {
    console.log(this.swiper);
    // this.swiper.slideTo(3, 1000, false)
  },
  methods: {
    onSwiper (swiper) {
      console.log(swiper);
    },
    onSlideChange () {
      console.log('slide change');
    }
  }
}
</script>

<style lang="less" scoped>
.swiper-box {
  overflow: hidden;
  & /deep/ .swiper-container {
    width: 100%;
    height: 300px;
    .swiper-slide {
      text-align: center;
      font-size: 18px;
      line-height: 300px;
      border: 1px solid red;
      box-sizing: border-box;
      transition: 300ms;
      transform: scale(0.8);
      &:hover {
        transform: scale(1);
      }
    }
  }
}
</style>

​​​​​​​

 类似资料: