vue的swiper組件 https://www.npmjs.com/package/vue-awesome-swiper
1、安裝 swiper 和 vue-awesome-swiper 插件
cnpm install swiper vue-awesome-swiper --save
(截圖里只安裝了vue-awesome-swiper,后面我又安裝了swiper,大家自己補充下)

2、在 components目錄下,創建slider目錄,導入圖片素材,創建index.vue
<template>
<swiper ref="mySwiper" :options="swiperOptions">
<swiper-slide v-for="(slider,index) in sliders" :key="index">
<a :href="slider.linkUrl">
<img :src="slider.imgUrl">
</a>
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
<div class="swiper-button-prev" slot="button-prev"></div>
<div class="swiper-button-next" slot="button-next"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
export default {
name:"Slider",
title: 'Autoplay',
components:{
Swiper,
SwiperSlide
},
data() {
return {
sliders:[
{
index:0,
linkUrl:'www.baidu.com',
imgUrl:require('./1.jpg')
},{
index:0,
linkUrl:'www.baidu.com',
imgUrl:require('./2.jpg')
},{
index:0,
linkUrl:'www.baidu.com',
imgUrl:require('./3.jpg')
},{
index:0,
linkUrl:'www.baidu.com',
imgUrl:require('./4.jpg')
}
],
swiperOptions: {
spaceBetween: 30,
centeredSlides: true,
autoplay: {
delay: 2500,
disableOnInteraction: false
},
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
}
}
},
computed: {
swiper() {
return this.$refs.mySwiper.$swiper;
}
},
mounted() {
console.log('Current Swiper instance object', this.swiper);
this.swiper.slideTo(3, 1000, false);
}
}
</script>
<style lang="scss" scoped>
.swiper-container{
width:100%;
height:180px;
}
.swiper-slide a{
display:block;
width:100%;
height:100%;
& img{
width:100%;
height:100%;
}
}
</style>
3、創建pages/home/index.vue,引入slider組件
<template>
<div class="home">
<slider/>
</div>
</template>
<script>
import Slider from 'components/slider';
export default {
name:"Home",
components:{
Slider
}
}
</script>
4、添加路由 src/router/index.js
import Vue from 'vue' import Router from 'vue-router' import Home from 'pages/home' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Home', component: Home } ] })
效果圖

需要注意的是:
如果在 DOM 結構中的某個 DOM 節點使用了 v-if、v-show 或者 v-for(即根據獲取到的后台數據來動態操作 DOM,即響應式),那么這些 DOM 是不會在 mounted 階段找到的。
mounted 階段,一般是用於發起后端請求,獲取數據,配合路由鈎子做一些事情。簡單來說就是在 mounted 鈎子中加載數據而已,加載回來的數據是不會在這個階段更新到 DOM 中的。所以在 mounted 鈎子中使用 $refs,如果 ref 是定位在有 v-if、v-for、v-show 的 DOM 節點中,返回來的只能是 undefined,因為在 mounted 階段他們根本不存在。
如果說 mounted 階段是加載階段,那么 updated 階段則是完成了數據更新到 DOM 的階段(對加載回來的數據進行處理),此時,再使用 this.$refs.xx,就 100% 能找到該 DOM 節點。
updated 與 mounted 不同的是,在每一次的 DOM 結構更新,Vue.js 都會調用一次 updated 鈎子函數!而 mounted 鈎子函數僅僅只執行一次而已。
因此修改mouted為updated如下:

