// 在main.js中全局定义<transition>函数式组件
Vue.component('my-special-transition', {
/*
* 设置functional: true则表示该组件为函数式组件
* 函数式组件定义:
* 没有管理任何状态,没有监听任何传递给它的状态,
* 没有生命周期方法,只是一个接收一些prop的函数
* 没有实例(没有this上下文)
* */
functional: true,
// 为了弥补缺少的实例,提供第二个参数作为上下文
render(createElement, context) {
var data = {
// 组件prop,下面的name和mode都会被设置在<transition>上
props: {
name: 'very-special-transition',
mode: 'out-in',
css: false
},
// 事件监听器
on: {
beforeEnter(el){
el.style.opacity = 0;
el.style.transform = 'translateY(-50px)'
},
// 当只用js过渡时,在enter和leave中必须使用done进行回调
enter(el, done){
// 注意:translateY动画效果无法应用于span等内联元素
Velocity(el, {opacity: 1, translateY: '0px'}, {complete: done})
},
leave(el, done){
Velocity(el, {opacity: 0, translateY: '50px'}, {complete: done})
},
}
};
/*
* 组件所需要的一切都是通过context参数传递
* context是一个包含如下字段的对象:
* props
* children
* VNode子节点的数组
* slots
* ...
* */
return createElement('transition', data, context.children)
/*
* 上面的data是一个与模板中attribute对应的数据对象
* */
}
});
// 在main.js中全局引入velocity.min.js
// Velocity 和 jQuery.animate 的工作方式类似,也是用来实现 JavaScript 动画的一个很棒的选择
// https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js
/*
* Velocity中文文档
* http://shouce.jb51.net/velocity/index.html
* */
import '@/assets/js/velocity.min.js'
<!-- Vue <transition> 用函数式组件实现可复用过渡动画案例-->
<template>
<div class="page">
<button @click="isHello = !isHello">click</button>
<my-special-transition>
<p v-if="isHello" key="hello">hello</p>
<p v-else key="world">world</p>
</my-special-transition>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
isHello: true
}
},
computed: {},
methods: {
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
</style>