vue2实现高度过渡效果,函数式组件
1.首先创建src下创建utils文件夹,创建transition.js文件封装过渡组件
const transitionStyle = '0.3s height ease-in-out' const Transition = { // 进入前 设置el元素的transition,高度0 beforeEnter (el) { el.style.transition = transitionStyle el.style.height = 0 }, // 进入中 enter (el) { // 获取元素显示的高度 if (el.scrollHeight !== 0) { el.style.height = `${el.scrollHeight}px` } else { //没有高度就不显示 el.style.height = '' } el.style.overflow = 'hidden' }, // 进入结束 afterEnter (el) { // 清除过度样式 el.style.transition = '' el.style.height = '' }, // 离开前 beforeLeave (el) { el.style.height = `${el.scrollHeight}px` el.style.overflow = 'hidden' }, // 离开中 leave (el) { if (el.scrollHeight !== 0) { el.style.transition = transitionStyle el.style.height = 0 } }, // 离开结束 afterLeave (el) { el.style.transition = '' el.style.height = '' } } export default { functional: true, //指定函数组件 render (h, {children}) { return h('transition', { on: Transition}, children) } }
过渡组件使用,直接在需要使用的组件引入注册
<template> <div> <p @click="show=!show">切换</p> <my-transition> <ul class='box' v-if="show"> <li>aaaaaaa</li> <li>bbbbbbb</li> <li>ccccccc</li> <li>ddddddd</li> <li>eeeeeee</li> </ul> </my-transition> </div> </template> <script> // 自定义过度组件 import myTransition from "../utils/transition.js"; export default { data() { return { show:false } }, components: { "my-transition": myTransition, }, } </script> <style lang="less" scoped> .box{ background: rgb(248, 248, 248); position: absolute; box-sizing: border-box; top: 50px; left: 40%; } </style>