微信小程序中的组件化开发可以使用 template 和 Component 两种方式来实现。
template 模板实现组件
template 模板是一种很简单的组件化方式,通常用于展示静态的内容。可以将页面中的某一段代码封装为一个 template 模板,再在需要使用的地方引入该模板即可。
下面以一个简单的自定义头部组件为例,先在 index.json 中定义好头部组件:
json
{
"usingComponents": {
"custom-header": "/components/header/header"
}
}然后在 components 文件夹下创建 header 文件夹,并在该文件夹下创建 header.wxml 和 header.wxss 两个文件,分别用于编写组件的模板和样式,例如:
header.wxml:
html
<view class="header">
<image class="logo" src="../images/logo.png"></image>
<text class="title">{{title}}</text>
</view>header.wxss:
css
.header {
display: flex;
align-items: center;
justify-content: center;
height: 60rpx;
background-color: #FFFFFF;
border-bottom: 1rpx solid #E6E6E6;
}
.logo {
width: 40rpx;
height: 40rpx;
}
.title {
font-size: 28rpx;
margin-left: 20rpx;
}在 header.js 中定义组件的属性:
js
Component({
/**
* 组件的属性列表
*/
properties: {
title: { // 页面标题
type: String,
value: '默认标题'
}
},
})最后在需要使用头部组件的页面中使用 <custom-header> 标签引用该模板文件,并传入需要显示的标题:
html
<custom-header title="首页"></custom-header>Component 构造器实现组件
Component 构造器是一种更灵活、更复杂的组件化方式,可以自定义组件的行为、事件等。下面以一个自定义列表组件为例,介绍如何使用 Component 构造器来实现组件化开发。
首先在 components 文件夹下创建 list 文件夹,并在该文件夹下创建 list.wxml 和 list.wxss 两个文件,分别用于编写组件的模板和样式,例如:
list.wxml:
html
<scroll-view class="list" scroll-y="true" bindscrolltolower="_loadMore">
<slot name="item"></slot>
</scroll-view>list.wxss:
css
.list {
width: 100%;
height: 100%;
}
.list::after {
content: "";
display: block;
padding-bottom: 20rpx; /* 预留底部距离 */
}在 list.js 中定义组件,并实现相应的逻辑:
js
Component({
options: {
multipleSlots: true // 启用多插槽支持
},
/**
* 组件的属性列表
*/
properties: {
hasMore: { // 是否还有更多数据
type: Boolean,
value: true
}
},
/**
* 组件的初始数据
*/
data: {},
/**
* 组件的方法列表
*/
methods: {
_loadMore() { // 加载更多数据
if (this.data.hasMore) {
this.triggerEvent('loadmore')
}
}
}
})在需要使用列表组件的页面中使用 <list> 标签引用该组件,并在插槽中插入需要展示的数据项:
html
<list has-more="{{hasMore}}" bind:loadmore="_loadMore">
<block wx:for="{{list}}" wx:key="index">
<slot name="item">
<view class="item">{{item.name}}</view>
</slot>
</block>
</list>在以上代码中,list 是一个数组,用于存储需要展示的数据。在组件的模板中使用 wx:for 遍历数据,并通过插槽传入 item 数据。
总而言之,这就是微信小程序代码组件化开发的基本流程。对于具体实现,可以根据项目需求和技术水平选择适合自己的方式进行组件化开发。









