您的位置:首页 > 移动开发 > 微信开发

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

2020-06-03 04:34 666 查看

在很多地方都有列表,我做的项目就有几个地方重复了列表,想着把它变成自定义组件。
效果图

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>
组件样式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: