纵横研究院小程序技术专题社区

微信小程序:swiper组件及自定义组件

2019-05-17  本文已影响248人  雷银

开发小程序的过程中,为避免一些重复性工作,可使用组件进行开发,达到一次制作,多次使用的效果。小程序组件可分为官方组件和自定义组件,本文将介绍swiper组件和自定义组件的使用。
1.swiper组件
swiper组件是滑块视图容器,主要用来做图片轮播。其中只能放置<swiper-item>组件,代码及效果图如下:

<view class="content">
  <swiper indicator-dots="true" autoplay="true" interval="2000">
    <swiper-item>
        <image src="../images/haibao/haibao-1.jpg"></image>
    </swiper-item>
    <swiper-item>
        <image src="../images/haibao/haibao-2.jpg"></image>
    </swiper-item>
    <swiper-item>
        <image src="../images/haibao/haibao-3.jpg"></image>
    </swiper-item>
  </swiper>
</view>

其中
indicator-dots=”true“表示显示面板指示点
autoplay="true"表示自动播放轮播图
interval=”2000“表示自动切换时间间隔为2s,单位是ms
更多属性可查看官方文档https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html

swiper组件效果图

2.自定义组件
(1)新建components文件夹,专门用于存放组件,在caipu文件夹右击新建component会自动生成生成4个文件,分别是js、json、wxml和wxss。


components结构

(2)在wxml和wxss文件中完成静态页面。
caipu.wxml

<view>
   <view class='item'>
      <view>
        <image src='{{item.img}}' style='width:75px;height:58px;'></image>
      </view>
      <view class='desc'>
        <view class='title'>{{item.title}}</view>
        <view class='count'>
          <view>{{item.type}}</view>
          <view class='liulan'>{{item.liulan}}</view>
          <view class='pinglun'>{{item.pinglun}}</view>
        </view>
      </view>
    </view>
    <view class='hr2'></view>
</view>

caipu.wxss

.item{
    display: flex;
    flex-direction: row;
    margin-left: 10px;
    margin-bottom:5px; 
    margin-top:5px;
}
.desc{
    margin-left: 20px;
    line-height: 30px;
}
.title{
    font-weight: bold;
}
.count{
    display: flex;
    flex-direction: row;
    font-size: 12px;
    color: #999999;
}
.liulan{
    position: absolute;
    right: 70px;
}
.pinglun{
    position: absolute;
    right: 10px;
}

(3)在caipu.json中声明自定义组件

{
  "component": true, // 声名组件
  "usingComponents": {} // 可引用其他组件
}

(4)设置caipu.js文件

Component({
  /**
  * 组件的属性列表
  */
  properties: {
    item: {            // 属性名
      type: Object,    // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: {
        img: '../../images/list/food-4.jpg',
        title: '搜狐新闻,手机用久了',
        type: '广告',
        liulan: '4688浏览',
        pinglun: '4评论'
      }    // 属性初始值(可选),如果未指定则会根据类型选择一个
    },
  },
  /**
  * 组件的初始数据
  */
  data: {
  },
  /**
  * 组件的方法列表
  */
  methods: {
  }
})

完成这步一个自定义组件就完成了,接下来就在文件中引入并使用它!
(5)在cook.json中引入该组件

{
  "usingComponents": {
    "caipu": "../components/caipu/caipu"
  }
}

(6)在cook.wxml中使用

<view class='list'>
 <block wx:for="{{array}}" wx:key="index">
   <caipu item="{{item}}"></caipu>
 </block>
</view>

一个简单的自定义组件的创建及使用就完成啦!
具体实现效果:


自定义组件效果图
上一篇 下一篇

猜你喜欢

热点阅读