原始链接:https://segmentfault.com/a/1190000021856837
转载链接:https://www.jianshu.com/p/d1ecb0c36765
想知道原理仔细看上面博文介绍
首先新建一个collapse-transition.js
文件放动画组件逻辑:
// collapse-transition.js,这个文件我是放在utils工具类中的
const transitionStyle = '0.3s height ease-in-out'
const Transition = {
beforeEnter (el) {
el.style.transition = transitionStyle
if (!el.dataset) el.dataset = {}
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) {
if (!el.dataset) el.dataset = {}
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 {
name: 'CollapseTransition',
functional: true,
render (h, {
children
}) {
const data = {
on: Transition
}
return h('transition', data, children)
}
}
然后在要用的父组件中引入:
import CollapseTransition from '@/utils/collapse-transition'; // 动画收缩组件
export default {
components: {
'collapse-transition': CollapseTransition
},
}
然后页面使用,用一个按钮控制收缩:
<collapse-transition>
<div class="cashbox-body expandBox searchBox" v-if="searchBoxShow">
... ...
</div>
</collapse-transition>
<el-button type="success" plain @click="searchBoxShow = !searchBoxShow">
搜索栏
<i class="el-icon-search el-icon--right"></i>
</el-button>
使用方法就这样,值得注意的是,我初次使用的时候,给<collapse-transition>
组件里面的盒子写了上下padding
,然后动画就会卡顿并且分段进行,可能和盒模型有关。