一、父传子
与vue利用props类似,小程序是利用自定义属性:properties
// components/my-nav/my-nav.js
Component({// 小程序组件默认样式是隔离,addGlobalClass设置为true可允许外部修改样式options: {addGlobalClass: true,// 只要使用到具名插槽,都需要将multipleSlots设置为truemultipleSlots: true},externalClasses: ["custom-class"],// 内部数据data: {statusBarHeight: 0},// 外部数据--父传子properties: {// back: Booleanback: {type: Boolean,value: false},delta: {type: Number,value: 1}},// 生命周期lifetimes: {created(){},attached() {const { statusBarHeight } = wx.getSystemInfoSync()console.log(wx.getSystemInfoSync())console.log(statusBarHeight)this.setData({statusBarHeight: statusBarHeight})}}
})
<view class="navigation-bar custom-class" style="padding-top: {{statusBarHeight}}px;"><view class="navigation-bar-title title-class"><text class="back-text" wx:if="{{ back }}" open-type="navigateBack" delta="{{ delta }}">返回</text><slot name="left"></slot>自定义标/题<slot name="right"></slot></view>
</view>
<app-nav custom-class="nav_title" back="{{ true }}" ><text slot="left">◀</text><text slot="right">▶</text>
</app-nav>
二、子传父
类似vue使用$emit方法,小程序利用triggerEvent和bind:自定义事件方法向父组件传递参数。
注意:小程序组件中的方法,要写在js的methods中
// components/my-nav/my-nav.js
Component({// 小程序组件默认样式是隔离,addGlobalClass设置为true可允许外部修改样式options: {addGlobalClass: true,// 只要使用到具名插槽,都需要将multipleSlots设置为truemultipleSlots: true},externalClasses: ["custom-class"],// 内部数据data: {statusBarHeight: 0},// 外部数据--父传子properties: {// back: Booleanback: {type: Boolean,value: false},delta: {type: Number,value: 1}},methods: {onTap() {// this.triggerEvent('自定义事件',参数)this.triggerEvent('getBarHeight',this.data.statusBarHeight)}},// 生命周期lifetimes: {created(){},attached() {const { statusBarHeight } = wx.getSystemInfoSync()console.log(wx.getSystemInfoSync())console.log(statusBarHeight)this.setData({statusBarHeight: statusBarHeight})}}
})
<view class="navigation-bar custom-class" style="padding-top: {{statusBarHeight}}px;"><view class="navigation-bar-title title-class"><text class="back-text" wx:if="{{ back }}" open-type="navigateBack" delta="{{ delta }}">返回</text><slot name="left" bind:tap="onTap"></slot>自定义标题<slot name="right"></slot></view>
</view>
<!-- 页面注册自定义组件 -->
<!-- <page-search /> -->
<app-nav custom-class="nav_title" back="{{ true }}" bind:getBarHeight="getBarHeightFn" ><text slot="left">◀</text><text slot="right">▶</text>
</app-nav>
// pages/component/index.js
Page({getBarHeightFn(e) {console.log(e.detail)}
})