Vue可复用过渡和动态过渡

时间:2023-03-09 22:35:40
Vue可复用过渡和动态过渡

前面的话

  本文将详细介绍Vue可复用过渡和动态过渡

可复用过渡

  过渡可以通过 Vue 的组件系统实现复用。要创建一个可复用过渡组件,需要做的就是将 <transition> 或者 <transition-group> 作为根组件,然后将任何子组件放置在其中就可以了

Vue.component('my-transition', {
template: `
<transition name="transition1" mode="out-in" @before-enter="beforeEnter" @after-enter="afterEnter">
<slot></slot>
</transition>
`,
methods: {
beforeEnter: function (el) {
// ...
},
afterEnter: function (el) {
// ...
}
}
})

  函数组件更适合完成这个任务

Vue.component('my-special-transition', {
functional: true,
render: function (createElement, context) {
var data = {
props: {
name: 'very-special-transition',
mode: 'out-in'
},
on: {
beforeEnter: function (el) {
// ...
},
afterEnter: function (el) {
// ...
}
}
}
return createElement('transition', data, context.children)
}
})

动态过渡

  在 Vue 中即使是过渡也是数据驱动的!动态过渡最基本的例子是通过 name 特性来绑定动态值

<transition v-bind:name="transitionName">
<!-- ... -->
</transition>

  用 Vue 的过渡系统来定义的 CSS 过渡/动画 在不同过渡间切换会非常有用

  所有的过渡特性都是动态绑定。它不仅是简单的特性,通过事件的钩子函数方法,可以在获取到相应上下文数据。这意味着,可以根据组件的状态通过 JavaScript 过渡设置不同的过渡效果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="dynamic-fade-demo" class="demo">
Fade In: <input type="range" v-model="fadeInDuration" min="0" :max="maxFadeDuration">
Fade Out: <input type="range" v-model="fadeOutDuration" min="0" :max="maxFadeDuration">
<transition :css="false" @before-enter="beforeEnter" @enter="enter" @leave="leave">
<p v-if="show">小火柴的蓝色理想</p>
</transition>
<button v-if="stop" @click="stop = show = false">运行动画</button>
<button v-else @click="stop = true">停止动画</button>
</div>
<script type="text/javascript" src="velocity.min.js"></script>
<script type="text/javascript" src="vue.js"></script>
<script>
new Vue({
el: '#dynamic-fade-demo',
data: {
show: true,
fadeInDuration: 1000,
fadeOutDuration: 1000,
maxFadeDuration: 1500,
stop: true
},
mounted() {
this.show = false
},
methods: {
beforeEnter(el) {
el.style.opacity = 0
},
enter(el, done) {
Velocity(el,{ opacity: 1 },{duration: this.fadeInDuration,complete:()=>{
done();
if (!this.stop){
this.show = false;
}
}
})
},
leave(el, done) {
Velocity(el,{ opacity: 0 },{duration: this.fadeOutDuration,complete:()=>{
done();
this.show = true;
}
})
},
},
})
</script>
</body>
</html>