element框架代码折叠,隐藏代码显示代码的效果实现
2020-03-18 本文已影响0人
前端蜗牛老师
这种效果实现的原理其实就是改变元素的高度。我在vue 项目中利用mixin混入
请看代码如下
import { addClass } from '../utils' // 增加类的方法
export const foldMixins = {
data() {
return {
foldStatus: false, // 搜索框是否折叠
flag: false
}
},
mounted() {
if (!this.flag) {
addClass(this.$refs.ruleForm.$el, 'fold-meta')
this.flag = true
} // 首次只添加一次类名
this.handleFold()
},
methods: {
handleFold() {
this.$refs.ruleForm.$el.style.overflow = 'hidden'
if (this.foldStatus) {
this.$refs.ruleForm.$el.style.height = 0 + 'px'
} else {
this.$refs.ruleForm.$el.style.height = 'auto'
}
this.foldStatus = !this.foldStatus
}
}
}
/**
* Add class to element
* @param {HTMLElement} elm
* @param {string} cls
*/
export function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += ' ' + cls
}
当然还需要创建一个功能组件 @/component/fold/index.vue
<template>
<div class="fold-wrapper" @click="_handleFold">
<div v-if="foldStatus" class="to-top">
<i class="el-icon-caret-top" />
<span>折叠</span>
</div>
<div v-if="!foldStatus" class="to-top">
<i class="el-icon-caret-bottom" />
<span>展开</span>
</div>
</div>
</template>
<script>
export default {
name: 'Fold',
props: {
foldStatus: {
type: Boolean,
default: false
}
},
methods: {
_handleFold() {
this.$emit('handleFold', true)
}
}
}
</script>
<style scoped lang="scss">
.fold-wrapper {
width: 100%;
border-top: 1px solid #eaeefb;
height: 44px;
line-height: 44px;
box-sizing: border-box;
background-color: #fff;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
text-align: center;
margin-top: -1px;
font-size: 12px;
color: #d3dce6;
cursor: pointer;
position: relative;
.to-top {
transition: all .3s;
span {
opacity: 0;
transition: all .3s;
}
&:hover {
color: #409eff;
transform: translateX(-20px);
span {
color: #409eff;
opacity: 1;
}
}
}
}
</style>
接下来就是在使用的地方引入
import fold from '@/components/fold'
import { foldMixins } from '@/mixins/fold'
export default {
components: { fold },
mixins: [foldMixins],
}
html 里在需要的地方加一下
<fold :fold-status="foldStatus" @handleFold="handleFold" />
就行了
image.png
image.png