0
点赞
收藏
分享

微信扫一扫

vue项目实战之图片画廊组件的实现

前言 笔者曾经写过不少或原生的、或封装的第三方插件的组件,总结来说,并不是所有东西都用原生,自定义的才是好的。很多插件做的也是不错的。就比如笔者今天所用的这个插件:vue-awesome-swiper ——这个还是很强的【轮播图】/【滚动】插件。非常的好用、方便。需要详细了解的可以去GitHub上搜索。

我们先来看下在项目中的实现效果:(将此组件引用到项目中即可)

vue项目实战之图片画廊组件的实现_ide

->

vue项目实战之图片画廊组件的实现_css_02

在项目中引入:

控制台:

cnpm install vue-awesome-swiper --save

在项目目录下的 main.js中

//...
import VueAwesomeSwiper from 'vue-awesome-swiper'
//...
import 'swiper/dist/css/swiper.css'

//...
Vue.use(VueAwesomeSwiper)

如何使用:

在项目src目录下新创建一个common文件夹——用于存放全局公用组件,在其下创建画廊组件文件夹gallay —— 存放组件Gallay.vue:

<template>
  <div class="container" @click="handleGallaryClick">
    <div class="wrapper">
      <swiper :options="swiperOptions">
        <swiper-slide
          v-for="(item, index) in imgs"
          :key="index"
        >
          <img class="gallary-img" :src="item" />
        </swiper-slide>

        <!-- 这是底部的数字显示 -->
        <div class="swiper-pagination" slot="pagination"></div>

      </swiper>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CommonGallary',
  props: {
    imgs: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      swiperOptions: {
        pagination: '.swiper-pagination',
        paginationType: 'fraction',   //分式表达
        observeParents: true,
        observer: true
      }
    }
  },
  methods: {
    handleGallaryClick () {
      this.$emit('close')
    }
  }
}
</script>

<style lang="stylus" scoped>
  .container >>> .swiper-container   /* 样式穿透——可以影响不同组件的元素 */
    overflow: inherit
  .container
    display: flex
    flex-direction: column
    justify-content: center
    z-index: 99
    position: fixed
    left: 0
    right: 0
    top: 0
    bottom: 0
    background: #000
    .wrapper
      height: 0
      width: 100%
      padding-bottom: 100%
      .gallary-img
        width: 100%
      .swiper-pagination
        color: #fff
        bottom: -1rem
</style>

上面data中不能有数据 —— 一个组件初始是不能有默认数据的,所以即使是怕ajax发送有误,也应将“默认数据”放到“主组件”中去。我们一般采用“外部传递”的方式,如 在页面组件中(引用):

<template>
	<div @click="handleBannerClick">此处是模拟点击窗口图标div</div>
	<common-gallary :imgs="imgs" v-show="showGallary"></common-gallary>
</template>

<script>
	import CommonGallary from './common/gallay/Gallary.vue';
	export default {
		data () {
			return {
				showGallary:false,
				imgs:['xxx','xxx']
			}
		},
		components: {
			CommonGallary
		},
		methods: {
			handleBannerClick () {
				this.showGallary=true;
			},
			close () {
				this.showGallary=false;
			}
		},
		//...
	}
</script>

让我们再来看下代码: 组件底部是显示页码 —— swiperOptions部分 怎么配置的呢? 我们在swiper标签中加了一个options动态属性:options="swiperOptions" ,在data(){}中,给它配置一个选项,就是slot -> pagination,它指向了所在div!

举报

相关推荐

0 条评论