vue项目笔记(25)-公共组件拆分

公共组件拆分(画廊组件)

vue项目开发中,有些组件不仅仅是一个页面需要使用,这时候我们可以将其抽离出来,作为一个公共组件。公共组件常用的目录结构如下(其中Gallery.vue就是公共组件):

Gallery.vue中的图片需要有轮播效果,故采用swiper,swiper中相关配置如下(详情参考swiper3官网):

在Gallery.vue组件中的轮播图片,需要使用v-for循环。而imgs是有父组件传过来的 ,在该组件中声明props接收,并在父组件中传递过来。

Gallery.vue

<template>
  <div class="container" @click="handleGalleryClick">
    <div class="wrapper">
      <swiper :options="swiperOption">
        <swiper-slide v-for="(item,index) in imgs" :key="index">
          <img class="gallery-img"
               :src="item">
        </swiper-slide>
        <div class="swiper-pagination" slot="pagination"></div>
      </swiper>
    </div>
  </div>
</template>
<script>
  export default{
    name: 'CommonGallery',
    props:{
      imgs:{
        type:Array,
        default () {
          return []
        }
      }
    },
    data(){
      return {
        swiperOption: {
          pagination: '.swiper-pagination',
          // 分页器样式类型,可选bullets-圆点(默认),fraction-分式,progress-进度条,custom-自定义
          paginationType: 'fraction',
          // 启动动态检查器(OB/观众/观看者),当改变swiper的样式(例如隐藏/显示)或者修改swiper的子元素时,自动初始化swiper。默认false,不开启,可以使用update()方法更新。
          observer:true,
          // 将observe应用于Swiper的父元素。当Swiper的父元素变化时,例如window.resize,Swiper更新。
          observeParents:true
        }
      }
    },
    methods:{
      handleGalleryClick(){
      this.$emit('close')
      }
    }
  }
</script>

Banner.vue

<template>
  <div>
    <div class="banner" @click="handleGalleryClick">
      <img class="banner-img"
           src="http://img1.qunarzz.com/sight/p0/1607/7c/7cda8b6782dabd80b4.img.jpg_600x330_8572a930.jpg">
      <div class="banner-info">
        <div class="banner-title">
          上海迪士尼乐园
        </div>
        <div class="banner-number">
          <span class="iconfont banner-icon">&#xe60f;</span>
          39
        </div>
      </div>
    </div>
    <common-gallery :imgs="imgs" v-show="showGallery" @close="handleGalleryClose"></common-gallery>
  </div>
</template>
<script>
  import CommonGallery from 'common/gallery/Gallery'
  export default{
    name: 'DetailBanner',
    data(){
      return {
        showGallery: false,
        imgs: ['http://img1.qunarzz.com/sight/p0/1607/7c/7cda8b6782dabd80b4.img.jpg_r_800x800_d6a63068.jpg', 'http://img1.qunarzz.com/sight/p0/1607/7c/7cda8b6782dabd80b4.img.jpg_r_800x800_d6a63068.jpg', 'http://img1.qunarzz.com/sight/p0/1607/7c/7cda8b6782dabd80b4.img.jpg_r_800x800_d6a63068.jpg']
      }
    },
    components: {
      CommonGallery
    },
    methods: {
      handleGalleryClick(){
        this.showGallery = true;
      },
      handleGalleryClose(){
        this.showGallery = false;
      }
    }
  }
</script>

解释:

(1)showGallery是布尔值,控制Gallery组件的显隐性。

(2)Gallery.vue与Banner.vue之间imgs传值属于父子传值。

(3)Gallery.vue调用Banner.vue中的方法,实现点击页面关闭画廊轮播图片。

猜你喜欢

转载自blog.csdn.net/qq_41115965/article/details/81748283