1、先準備好一個api介面 http://www.imooc.com/api/home/slider 2、安裝插件 cnpm install --save axios 3、api/slider.js import axios from 'axios'; //獲取幻燈片數據 ajax export c ...
1、先準備好一個api介面 http://www.imooc.com/api/home/slider
2、安裝插件 cnpm install --save axios
3、api/slider.js
import axios from 'axios'; //獲取幻燈片數據 ajax export const getSliders=()=>{ return axios.get('http://www.imooc.com/api/home/slider').then(res=>{ if(res.data.code===0){ console.log(res.data.slider); return res.data.slider;//返回是數據 } throw new Error('沒有成功獲取到數據'); }).catch(err=>{ console.log(err); //錯誤處理 return [{ linkUrl:'www.baidu.com', picUrl:require('assets/img/404.png') }] }); }
4、在 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.picUrl"> </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'; import { getSliders } from 'api/slider'; export default { name:"Slider", title: 'Autoplay', components:{ Swiper, SwiperSlide }, data() { return { sliders:[], 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' } } } }, created(){ //一般在created里獲取遠程數據 this.getSliders(); }, computed: { swiper() { return this.$refs.mySwiper.$swiper; } }, mounted() { //console.log('Current Swiper instance object', this.swiper); this.swiper.slideTo(3, 1000, false); }, methods:{ getSliders(){ return getSliders().then(data=>{ //console.log(data); this.sliders=data; }); } } } </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>
效果圖