小程序自定义组件

129 阅读1分钟

步骤:

1、创建组件
(1)创建组件文件
1645956919(1).jpg
(2)编辑组件

<!--component/SwiperItem/SwiperItem.wxml-->
<swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" 
 interval="{{interval}}" duration="{{duration}}">
    <block wx:for="{{list}}" wx:key="index">
      <swiper-item class="item" data-url="{{item.path}}" bindtap="go">
        <image src="{{item.image}}" class="img1" mode="widthFix"></image>
      </swiper-item>
    </block>
</swiper>

/* component/SwiperItem/SwiperItem.wxss */
.item{
  width: 750rpx;
}
.img1{
  width: 100%;
  display: block;
}

// component/SwiperItem/SwiperItem.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
      list:{
        type:Array,
        value:[]
      }
  },

  /**
   * 组件的初始数据
   */
  data: {
    indicatorDots:true,
    autoplay:true,
    interval:1500,
    duration:500
  },

2、使用组件
(1)在页面json文件中配置组件路径

1645957123(1).jpg
(2)使用组件
1645957179(1).jpg

组件传值

1、父传子
1645957466(1).jpg

// component/SwiperItem/SwiperItem.js
Component({
  /**
   * 组件的属性列表 来接收父组件传过来的对象
   */
  properties: {
      list:{
        // 表明数据类型
        type:Array, 
        // 如果没有数据时的默认值
        value:[]
      }
  },

2、子传父
(1)子组件绑定事件 1645957776(1).jpg
(2)在子组件的方法列表中定义事件

/**
   * 组件的方法列表
   */
  methods: {
    go(e){
      let {currentTarget:{dataset:{url}}}=e;
      // goNewPage 子组件自定义的事件名称
      // url 子组件传给父组件的数据
      this.triggerEvent('goNewPage',url)
    }
  }

(3)父组件绑定子组件的事件

1645958023(1).jpg
(4)在父组件的js文件中定义事件

goNewPage(e){
    // console.log(e);
    // 子组件传过来的数据存在 e.detail 中
    wx.navigateTo({
      url: '/pages/linkpage/linkpage?url='+e.detail,
    })
  },

组件使用插槽

1645958252(1).jpg