nuxt.js框架引入swiper

795 阅读1分钟

前言

因为公司的需求,我需要实现多种轮播图的效果,从头做起是不可能的,于是我想到了以前用过的swiper插件,刚好nuxt也有支持swiper的vue-awesome-swiper插件,二话不说直接上手。

导入插件,实现效果,完成需求。如果这么顺利的话,就不会有这个文章了~不出意外的,我在导入插件时出了意外,在看了很多教程之后感觉是版本的问题,因为用的是nuxt2,安装的swiper版本都不能是最新的,试了几个版本终于好了~~

正文

1. 安装swiper

先删除之前的版本

npm uninstall swiper --save
npm uninstall vue-awesome-swiper --save
npm install swiper@5.4.5 vue-awesome-swiper@4.1.1 --save

2. 在plugins下新建vue-swiper.js文件

import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'

Vue.use(VueAwesomeSwiper)

3. 在nuxt.config.js中引入

export default {
    //其他代码
    
    css: ['swiper/css/swiper.css'],
    plugins: ['@/plugins/vue-swiper'],
    
    //其他代码
}

4. swiper使用范例

<template>
  <div class="example-3d">
    <swiper ref="mySwiper" class="swiper" :options="swiperOptions">
      <swiper-slide>Slide 1</swiper-slide>
      <swiper-slide>Slide 2</swiper-slide>
      <swiper-slide>Slide 3</swiper-slide>
      <swiper-slide>Slide 4</swiper-slide>
      <swiper-slide>Slide 5</swiper-slide>
      <div slot="pagination" class="swiper-pagination"></div>
    </swiper>
  </div>
</template>

<script>
export default {
  name: 'Carrousel',
  data() {
    return {
      swiperOptions: {
        effect: 'coverflow',
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: 'auto',
        coverflowEffect: {
          rotate: 50,
          stretch: 0,
          depth: 100,
          modifier: 1,
          slideShadows: true,
        },
        pagination: {
          el: '.swiper-pagination',
        },
      },
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper
    },
  },
  mounted() {
    // eslint-disable-next-line no-console
    console.log('Current Swiper instance object', this.swiper)
    this.swiper.slideTo(0, 1000, false)
  },
}
</script>

<style>
.example-3d {
  width: 100%;
  height: 400px;
  padding-top: 50px;
  padding-bottom: 50px;
}

.swiper {
  height: 100%;
  width: 100%;
}

.swiper .swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 300px;
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  background-color: #2c8dfb;
  background-position: center;
  background-size: cover;
  color: #fff;
}
</style>

具体swiper配置可以参考swiper中文网文档