Vue <transition> 用函数式组件实现可复用过渡动画案例

 

 

// 在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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值