组件中要有props接收一个值,比如:show;组件的template中transition和slot的结合,可以接收父组件中的标签;过渡效果通过js钩子函数实现。这样就可以实现自己封装过渡动画,在项目中复用。
<body>
<div id="demo">
<button @click="show = !show">add item</button>
<fade :show="show">
<h4>hello world</h4>
</fade>
</div>
<script type="application/javascript">
Vue.component('fade', {
props: ['show'],
template: `<transition @before-enter="handleBeforeEnter"
@enter="handleEnter"
@after-enter="handleAfterEnter">
<slot v-if="show"></slot>
</transition>`,
methods: {
handleBeforeEnter(dom){
dom.style.color = 'red'
},
handleEnter (dom, done) {
setTimeout(() => {
dom.style.color = 'green'
}, 2000);
setTimeout(() => {
done()
}, 3000);
},
handleAfterEnter (dom) {
console.log('finish encapsulation')
}
}
})
new Vue({
el: '#demo',
data: {
show: true
},
})
</script>
</body>