微信小程序案例:自定义组件

在很多地方都有列表,我做的项目就有几个地方重复了列表,想着把它变成自定义组件。
效果图
在这里插入图片描述
1.首先创建组件文件夹,以及shopList文件夹,右击选择新建component,自动创建。
在这里插入图片描述
2.首先我们需要声明自定义组件
在这里插入图片描述
3.在wxml中搭建界面

<view class="list">
      <view wx:for="{{selectedList}}" wx:key class="item">
          <image src="http://114.215.172.115:8080/img/14ce36d3d539b6003ba874c9e550352ac65cb76d.jpg" class="item_img"></image>
          <view class="item_des">
            <text class="item_title">{{item.title}}</text>
            <text class="item_momey">{{item.money}}</text>
          </view>
      </view>
  </view>

4.shopList.wxss

.item_momey{
  color:red;
}
.item_img{
  width: 150rpx;
  height: 150rpx;
  background-size: 100%;
  margin-right: 20rpx;
}

.item{
  display: flex;
  margin: 20rpx;
}
.item_des{
  display: flex;
  flex-direction: column;
  margin-top: 10rpx;
  justify-content: space-around;
}
.list{
  margin: 20rpx;
}

5.shopList.js

// commpents/shopList.js
Component({
  /**
   * 组件的属性列表
   * 用于组件自定义设置
   */
  properties: {
    selectedList:{  // 属性名
      type:Array,// 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value:[]  // 属性初始值(可选),如果未指定则会根据类型选择一个
    }
  },

   /**
   * 私有数据,组件的初始数据
   * 可用于模版渲染
   */
  data: {

  },

  /**
   * 组件的方法列表
   * 更新属性和数据的方法与更新页面数据的方法类似
   */
  methods: {

  }
})

5.slot的使用
在小程序的官方文档中,按照步骤就可以使用了。注意:在wx:for中只能创建出一个slot。

<!-- 组件模板 -->
<view class="wrapper">
  <slot name="before"></slot>
  <view>这里是组件的内部细节</view>
  <slot name="after"></slot>
</view>
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: { /* ... */ },
  methods: { /* ... */ }
})
<!-- 引用组件的页面模板 -->
<view>
  <component-tag-name>
    <!-- 这部分内容将被放置在组件 <slot name="before"> 的位置上 -->
    <view slot="before">这里是插入到组件slot name="before"中的内容</view>
    <!-- 这部分内容将被放置在组件 <slot name="after"> 的位置上 -->
    <view slot="after">这里是插入到组件slot name="after"中的内容</view>
  </component-tag-name>
</view>
组件样式
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值