前言:在不同的页面重复使用自定义组件;自定义组件可以理解一个页面,在不同页面显示出来,一个自定义的组件也是由json、wxml、wxss、js 4个文件组成的,下面点击tabar页面切换显示自定义顶部为示例。
官网:https://developers.weixin.qq.com/miniprogram/dev/reference/api/Component.html
gif效果图片-最终效果:
目录结构
一.创建自定义组件
注:在"pages": []里面需要写自定义组件的路径
PS:组件代码-header.wxml
<view style="background:#e93323;height:{{navH}}rpx;">
<view style='height:{{navH}}rpx;position: relative;'>
<view style="position: absolute;bottom: 0;width: 100%;height: 100rpx;align-items: center;display: flex;justify-content: space-around;">
<view style="color: white;font-size: 30rpx;font-weight: bold;">{{parameter.title}}</view>
</view>
</view>
</view>
PS:组件代码-header.js
注:data里面的navH是在app.js获取的屏幕高度并且计算返回的自定义顶部的高度
var app = getApp();
Component({
properties: {
parameter: {
type: Object
}
},
data: {
navH: ''
},
attached: function() {
this.setData({
navH: app.globalData.navHeight
});
}
})
PS:组件代码-header.json
{
"usingComponents": {},
"component": true
}
PS:app.js代码
App({
onLaunch: function() {
// 获取导航高度;
wx.getSystemInfo({
success: res => {
//导航高度
this.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 97;
},
fail(err) {}
});
},
globalData:{
navHeight: 0,
},
globalData: {
userInfo: null
}
})
二.引入组件-index首页为例
1、index.json
PS:header是自定义的组件名称,在wxml调用;disableScroll是禁止下拉
{
"usingComponents": {
"header": "/components/header/header"
},
"disableScroll": true
}
2、index.wxml
PS:parameter是属性名称,上面gif图片可以看到切换到不同的页面顶部的文字会发生改变,也就是tabar页面的data里面定义了parameter的title
<header parameter='{{parameter}}'></header>
<view>首页页面</view>
3、index.js
Page({
data: {
parameter: {
'title': '首页'
},
}
})