1、props和$broadcast
父组件中的写法
<view class="time-out">
<view>剩余</view>
<GroupShopTimer :childrentips="tips"></GroupShopTimer>
</view>
item定义在父组件的data中:Item:{}
子组件中的写法
<template>
<view class="group-shop-timer">
<view wx:if="{{childrentips.hours}}"><text>{{timeout.hours}}</text>时</view>
<view wx:if="{{childrentips.minutes}}"><text>{{timeout.minutes}}</text>分</view>
<view wx:if="{{childrentips.seconds}}"><text>{{timeout.seconds}}</text>秒</view>
</view>
</template>
<script>
import wepy from 'wepy'
export default class GroupShopTimer extends wepy.component {
data={
timeout:{},
inv:-1,
group:{}
}
props={
childrentips:{
type:Object,
default:{
hours:true,
minutes:true,
seconds:true
}
}
}
events = {
loadTimeout(option){
this.group = option;
this.startTimeout(this.group);
}
}
onLoad(){
}
startTimeout(group){
clearInterval(this.inv);
let future = group.end_time;
this.inv = setInterval(()=>{
let date = new Date();
let now = date.getTime();
if(now>future)retrun;
let diff = future - now;
let hours = parseInt(diff / 1000 / 60 / 60, 10); //计算剩余的小时数
let minutes = parseInt(diff / 1000 / 60 % 60, 10); //计算剩余的分钟数
let seconds = parseInt(diff / 1000 % 60, 10); //计算剩余的秒数
if (hours < 0 || minutes < 0 || seconds < 0) {
clearInterval(this.inv);
}
this.timeout = {hours,minutes,seconds}
this.$apply()
},500)
}
}
</script>
这个一个计时器的组件
props={
childrentips:{
type:Object,
default:{
hours:true,
minutes:true,
seconds:true
}
}
}
子组件中自定义了一个childrentips属性,利用children对象中的hours,minutes,seconds的值结合wx:if方法来控制是否显示,父组件通过向子组件自定义childrentips属性中传值tips(tips可以定义在data中也可以直接写在双引号中“{hours:true,minutes:false,seconds:false}”)这样显示的只有hour。
注意:.sync后缀是在进行动态传值时所必须的
父组件利用$broadcast事件,触发定义在子组件events中的事件。不多说直接上代码
父组件:
this.$broadcast('loadTimeout',this.group)
$broadcast事件接受多个参数,第一个为定义在子组件events中需要触发的事件名称,后面的为要传递的参数.
events = {
loadTimeout(option){
this.group = option;
this.startTimeout(this.group);
}
}
startTimeout函数是对传过来的数据进行处理,可以自己研究一下。
注意:如果一个父组件有多个子组件,并且在子组件events中都定义了一个同名事件,那么只需要执行一次$broadcast事件就可以,全部触发。
2.$emit事件子组件向父组件传值
$emit通信的方式与$broadcast相同
没错,只要把要触发的事件写在父组件的events中,在子组件中使用$emit事件来触发父组件中的事件就可以啦。