子组件:
在根目录上建立一个components的文件夹,在里面自定义一个文件
timeChoose.json
{ "component": true, "usingComponents": {} }
timeChoose.wxml
<view class="cu-form-group"> <view class="title">开始</view> <picker mode="date" value="{{s_time}}" start="2015-09-01" end="2020-09-01" bindchange="DateChange" data-index="1"> <view class="picker"> {{s_time}} </view> </picker> <view class="title" >结束</view> <picker mode="date" value="{{e_time}}" start="2015-09-01" end="2020-09-01" bindchange="DateChange" data-index="2"> <view class="picker"> {{e_time}} </view> </picker> </view>
timeChoose.js
Component({ /** * 组件的属性列表 */ properties: { // 左侧标题 s_time: { // 属性名 type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) value: "" // 属性初始值(可选),如果未指定则会根据类型选择一个 }, e_time: { type: String, value: "" } }, data: { }, /** * 组件的方法列表 */ methods: { DateChange(e) { let index = e.currentTarget.dataset.index; if (index == 1) { this.setData({ s_time: e.detail.value }) this.triggerEvent("timeOut", { s_time: e.detail.value }) } else { this.setData({ e_time: e.detail.value }) this.triggerEvent("timeOut", { e_time: e.detail.value }) } }, popView: function () { // 注册点击事件传给父组件 this.triggerEvent("popView",12121) } } })
*注意这里的js里不是Page而是Component;
父组件:
父组件下的.json代码
{ "usingComponents": { "timeChoose": "/components/timeChoose/timeChoose", } }
父组件下的.wxml代码
<timeChoose s_time="{{startDate}}" e_time="{{endDate}}" bind:timeOut="timeOut"></timeChoose>
父组件下的.js代码
Page({ data: { startDate: "2018-12-25", endDate: "2019-09-01", }, timeOut: function (e) { if(e.detail.s_time){ this.setData({ startDate: e.detail.s_time }) }else{ this.setData({ endDate: e.detail.e_time }) } this.getList(); } })