Vue中的動畫封裝

如下代碼是實現點擊按鈕使文字漸隱漸現的隱藏和顯示的功能:html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Vue中的進場和出場過渡</title>
    <script src="./vue.js"></script>
    <style>
        .v-enter,
        .v-leave-to{
            opacity:0;
        }
        .v-enter-active,
        .v-leave-active{
            transition: opacity 1s;
        }
 
    </style>
</head>
<body>
    <div id="root">
        <transition>
            <div v-if="show">hello world</div>
        </transition>
        <button @click="handleClick">toggle</button>
    </div>
    <script >
        var vm = new Vue({
            el:'#root',
            data:{
                show:true
            },
            methods:{
                handleClick:function() {
                    this.show =!this.show
                }
            }
        })
 
    </script>
</body>
 
</html>

對應經常使用的動畫效果,能夠將其進行封裝起來,供其餘模塊調用,下降重複打碼的開發。vue

使用要封裝的內容寫成組件,並用slot插槽接管組件內容,就能實現動畫封裝了。代碼以下:segmentfault

 

<div id="root">
    <fade :show="show">
        <div>hello world</div>
    </fade>
    <button @click="handleClick">toggle</button>
</div>


Vue.component('fade',{
    props:['show'],
    template:`<transition name="fade">
                <slot v-if="show"></slot>
             </transition>`
})

 

動畫封裝不只能夠封裝內容也能夠封裝動畫樣式,這時候就不須要CSS樣式而是使用JS動畫將其一塊兒封裝在組件裏。代碼以下:動畫

Vue.component('fade', {
    props: ['show'],
    template: `
    <transition 
     @before-enter="handleBeforeEnter" @enter="handleEnter" @after-enter="handleAfterEnter"> <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) }, handleAfterEnter: function(el) { el.style.color = '#000' } } })

上面代碼用了JS提供的鉤子動畫before-enterenterafter-enter,用這種方法寫,全部的動畫都寫在了組件裏,外部只須要調用這個fade組件就能夠了,也不須要全局去寫一些樣式了,這種動畫的封裝是比較推薦的一種動畫封裝,由於它能夠把全部動畫的實現完整的封裝在一個組件中。this

 

 

參考文章:http://www.javashuo.com/article/p-xymmowlc-he.htmlspa

相關文章
相關標籤/搜索