最近在开发个人微信小程序,由于每个页面的布局基本相似,所以用到了自定义组件来简化开发。
创建自定义组件
这里以 header 组件作为例子,需要分别创建4个类型的文件如图:
文件内容
header.json
header.json 中需要添加 component: true
,声明该目录是一个组件。
{
"component": true,
"usingComponents": {}
}
header.wxml
小程序组件默认只支持一个 slot,如果需要多个 slot 需要在 header.ts 文件中 加入 options.multipleSlots: true
。
<view class="header">
<image class="avatar" src="{{src}}" mode="cover" bindtap="onTap"></image>
<view class="nav">
<slot></slot>
</view>
</view>
header.ts
通过 properties 属性声明组件接收的参数的 key
value
和类型。
Component({
properties: {
src: {
type: String,
value: '',
},
},
methods: {
onTap() {
wx.navigateTo({
url: '../../pages/index/index',
})
},
}
})
header.wxss
组件的样式默认只在组件内部有效,选择器只能使用 class 选择器,同时不建议使用子选择器
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
}
.header .avatar {
height: 60px;
width: 60px;
border-radius: 30px;
}
.header .nav {
display: flex;
padding: 0;
}
使用组件
使用组件之前需要先进行声明,在 index.json 中加入:
{
"usingComponents": {
"my-header": "../../components/avatar/header"
}
}
<view class="container">
<header src="{{meta.avatar.publicUrl}}">
<slot>
<navigator url="/pages/contact-me/index">Contact</navigator>
<navigator url="/pages/about/index">About</navigator>
</slot>
</header>
</view>
最终效果
结语
开发过程中微信开发工具随缘闪退,不知道为啥。还有就是组件样式开始不生效,按照网络搜到的方法试了之后OK了:
在开发者工具调试器中输入openVendor并回车;
开发者工具会打开一个文件夹,请删除这个文件夹下的所有文件;
关闭并重启开发者工具,看看这个问题是否还存在。