在需要使用swiper的组件里引入swiper,swiper的初始化放在mounted里(可以把官网例子的启动 var mySwiper = 删掉);
<script> import Swiper from 'swiper'; export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, mounted(){ new Swiper ('.swiper-container', { loop: true, // 如果需要分页器 pagination: '.swiper-pagination', // 如果需要前进后退按钮 nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', // 如果需要滚动条 scrollbar: '.swiper-scrollbar', }) } } </script>css: 在main.js里引入css
import Vue from 'vue' import 'swiper/dist/css/swiper.css'; <style scoped> .swiper-container { width: 500px; height: 300px; margin: 20px auto; } </style>二:全局使用: 当然也可以全局使用swiper;代码如下; 还是在刚才的helloworld.vue进行代码编写;只是去掉js和css文件的引入! helloworld.vue代码
<template> <div class="hello"> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide">Slide 1</div> <div class="swiper-slide">Slide 2</div> <div class="swiper-slide">Slide 3</div> </div> <!-- 如果需要分页器 --> <div class="swiper-pagination"></div> <!-- 如果需要导航按钮 --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> <!-- 如果需要滚动条 --> <div class="swiper-scrollbar"></div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, mounted(){ var mySwiper = new Swiper ('.swiper-container', { loop: true, // 如果需要分页器 pagination: '.swiper-pagination', // 如果需要前进后退按钮 nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', // 如果需要滚动条 scrollbar: '.swiper-scrollbar', }) } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> body { margin: 0; padding: 0; } .swiper-container { width: 500px; height: 300px; margin: 20px auto; } </style>