wepy元件控制彈窗淡入淡出,父元件控制內容與顯示事件
阿新 • • 發佈:2018-11-13
描述
- 父元件載入子元件
- 父元件傳值給子元件(顯示內容,顯示時長)
- 重複點選同一事件或者不同事件單個顯示時長不變(清理定時器)
- 類似彈窗都可轉換
程式碼
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()及時繫結
- 注意定時器的清理位置