wepy組件控制彈窗淡入淡出,父組件控制內容與顯示事件

描述

  1. 父組件加載子組件
  2. 父組件傳值給子組件(顯示內容,顯示時長)
  3. 重複點擊同一事件或者不同事件單個顯示時長不變(清理定時器)
  4. 類似彈窗都可轉換

代碼

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>

注意幾點

  1. 父子組件之間的傳值綁定
  2. 所有的處理最好都在子組件處理,父組件只實現調用,越簡單越好
  3. 子組件的函數處理可以在監聽函數裏面完成(watch = {})
  4. 需要馬上綁定數據改變的最好用$apply()及時綁定
  5. 注意定時器的清理位置
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章