本文實例為大家分享了vue動畫封裝的具體代碼,供大家參考,具體內容如下
<style> .v-enter,.v-leave-to{ opacity: 0; } .v-enter-active,.v-leave-active{ transition:opacity 1s; } </style> <div id='app'> <transition> <div v-if='show'>hello world</div> </transition> <button @click='handleClick'>切換</button> </div> <script> var vm = new Vue({ el:'#app', data:{ show:true }, methods:{ handleClick:function(){ this.show = !this.show; } } }) </script>
有時候這種漸隱漸現的效果用的比較多,要復用,需要封裝一下,怎么封裝呢
<style> .v-enter,.v-leave-to{ opacity: 0; } .v-enter-active,.v-leave-active{ transition:opacity 1s; } </style> <div id='app'> <fade :show='show'> <div>hello world</div> </fade> <fade :show='show'> <h1>hello world</h1> </fade> <button @click='handleClick'>切換</button> </div> <script> Vue.component('fade',{ props:['show'], template: ` <transition> <slot v-if='show'></slot> </transition> ` }) var vm = new Vue({ el:'#app', data:{ show:false }, methods:{ handleClick:function(){ this.show = !this.show; } } }) </script>
可以這樣封裝,將dom元素傳入slot,除了這樣,還可以樣式一起封裝進去
<div id='app'> <fade :show='show'> <div>hello world</div> </fade> <fade :show='show'> <h1>hello world</h1> </fade> <button @click='handleClick'>切換</button> </div> <script> Vue.component('fade',{ props:['show'], template: ` <transition @before-enter='handleBeforeEnter' @enter='handleEnter'> <slot v-if='show'></slot> </transition> `, methods:{ handleBeforeEnter:function(el){ el.style.color='red' }, handleEnter:function(el,done){ setTimeout(()=>{ el.style.color='green'; done(); },2000) } } }) var vm = new Vue({ el:'#app', data:{ show:false }, methods:{ handleClick:function(){ this.show = !this.show; } } }) </script>
把樣式一起封裝進來,是比較推薦的方式。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com