微信小程序自定义组件-自定义顶部-Component

前言:在不同的页面重复使用自定义组件;自定义组件可以理解一个页面,在不同页面显示出来,一个自定义的组件也是由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': '首页'
    },
  }
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值