版权声明:转载请附上本人id https://blog.csdn.net/qq_40414159/article/details/84026514
描述
- 父组件加载子组件
- 父组件传值给子组件(显示内容,显示时长)
- 重复点击同一事件或者不同事件单个显示时长不变(清理定时器)
- 类似弹窗都可转换
代码
father.wpy //父组件
<template>
<child :msg.sync="fmsg" :time.sync="ftime"></child> //调用子组件
<button @tap="clicked('welcome',2)">1</button> //测试事件(可以换成自己需要的事件)
<button @tap="clicked('海小玉',3)">2</button>
</template>
<script>
import wepy from 'wepy';
import Child from "../components/child"; //引用子组件
export default class Food extends wepy.page {
config = {
navigationBarTitleText: "弹窗淡入淡出",
backgroundColor: "#F5F4F5"
}
data = {
ftime: 3,
fmsg: ''
}
components = {
child: Child
}
methods = {
clicked(msg, time) {
this.fmsg = msg;
this.ftime = time;
}
child.wpy //子组件
<template>
<view class="com {{inout?'in':'out'}}">{{msg}}</view> //利用class控制淡入淡出样式
</template>
<script>
import wepy from 'wepy'
export default class Child extends wepy.component {
props = { //定义属性
msg: {
type: String, //类型
default: '', //默认值
twoWay: true //与父组件配合实现双向绑定
},
time: {
type: Number,
default: 3,
twoWay: true
},
}
data = {
inout: false,
timer: '' //声明定时器
}
watch = { //监控
msg(newValue, oldValue) { //监控msg变化
var me = this;
if (newValue) {
if (this.timer) { //清理定时器
clearTimeout(this.timer);
}
this.inout = true;
this.$apply(); //及时手动绑定,否则会出错
this.timer = setTimeout(() => { //设置定时器
me.inout = false; //内容显示完毕后进行淡出效果
me.$apply();
setTimeout(() => { //为了防止msg突然消失
me.msg = '';
me.$apply();
}, 500);
}, this.time * 1000)
}
}
}
onLoad() {
console.log('child 被调') //测试子组件是否被调用
}
}
</script>
<style lang="less">
.com {
position: absolute;
top: 0;
left: 0;
right: 0;
margin: 0 auto;
z-index: 10;
width: 400rpx;
height: 60rpx;
line-height: 60rpx;
border-radius: 10rpx;
text-align: center;
font-size: 32rpx;
background-color: pink;
opacity: 0;
transition: all .5s; //过渡时间(淡入淡出动画时间)
}
.in {
opacity: 1;
}
.out {
opacity: 0;
}
</style>
注意几点
- 父子组件之间的传值绑定
- 所有的处理最好都在子组件处理,父组件只实现调用,越简单越好
- 子组件的函数处理可以在监听函数里面完成(watch = {})
- 需要马上绑定数据改变的最好用$apply()及时绑定
- 注意定时器的清理位置