1. 程式人生 > >Vue元件(一)——Swiper輪播元件

Vue元件(一)——Swiper輪播元件

Vue輪播元件,詳情參見: awesome-swiper

  1. vue專案中安裝awsome-swiper元件:      npm  install   [email protected]  --save 
    (@2.6.7是元件的版本號)
  2. 全域性使用swiper外掛,需要在main.js檔案中引入swiper外掛
    import Vue from 'vue'
    import VueAwesomeSwiper from 'vue-awesome-swiper'
    // require styles
    import 'swiper/dist/css/swiper.css'
    
    
    Vue.use(VueAwesomeSwiper)
  3. 輪播元件
    <template>
      <div class="wrapper">
        <swiper :options="swiperOption" v-if="showSwiper">
          <swiper-slide v-for="item of list" :key="item.id">
            <img class="swiper-img" :src="item.imgUrl"/>
          </swiper-slide>
          <div class="swiper-pagination"  slot="pagination"></div>
        </swiper>
      </div>
    </template>
    
    <script>
    export default{
      name: 'HomeSwiper',
      props: {
        list: Array
      },
      data () {
        return {
          swiperOption: {
            pagination: '.swiper-pagination',
            loop: true
          }
        }
      },
      computed: {
        showSwiper () {
          return this.list.length
        }
      }
    }
    </script>
    
    <style lang="stylus" scoped>
      .wrapper >>> .swiper-pagination-bullet-active
          background: #fff !important
      .wrapper
        overflow: hidden
        width: 100%
        height: 0
        padding-bottom: 26.67%
        .swiper-img
          width: 100%
          background: #eee
    </style>
    
  4. 父元件引入輪播外掛,並完善swiperList物件陣列(JSON格式)
    <template>
      <div>
        <home-swiper :list="swiperList"></home-swiper>
      </div>
    </template>
    
    <script>
    import HomeSwiper from './components/Swiper'
    export default{
      name: 'Home',
      components: { // 宣告元件
        HomeSwiper: HomeSwiper
      },
      data () {
        return {
          swiperList: [],
        }
      }
    }
    </script>