工作需求,需要写一个垂直下拉菜单,然后我就自己在vue里面写了一个菜单,代码在下面仅供参考。
<template>
<div>
<div id="biao" @click="open('nei1')">标题1</div>
<ul ref="nei1">
<li>内容1</li>
<li>内容2</li>
<li>内容3</li>
</ul>
<div id="biao" @click="open('nei2')">标题2</div>
<ul ref="nei2" >
<li>内容1</li>
<li>内容2</li>
<li>内容3</li>
</ul>
<div id="biao" @click="open('nei3')">标题3</div>
<ul ref="nei3" >
<li>内容1</li>
<li>内容2</li>
<li>内容3</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
flag :true,
}
},
methods:{
open(n) {
console.log(this.$refs[n].style.maxHeight==='')
if(this.$refs[n].style.maxHeight==='') {
this.$refs[n].style.maxHeight = '600px';
this.$refs[n].style.transition = 'max-height .3s';
console.log(1)
} else {
this.$refs[n].style.maxHeight = '';
this.$refs[n].style.transition = '';
console.log(2)
}
}
}
}
</script>
<style scoped>
#biao {
width: 200px;
height: 50px;
background-color: aquamarine;
border: 1px solid #eeeeee
}
ul {
margin: 0;
padding: 0;
max-height: 0;
overflow: hidden;
-webkit-transition: max-height .3s;
transition: max-height .3s;
}
/* .open {
max-height: 600px;
-webkit-transition: max-height .3s;
transition: max-height .3s
} */
ul li{
width: 200px;
height: 35px;
background-color: blueviolet;
list-style: none;
}
</style>
本来想用类添加,但发现如何给元素添加和删除类是个问题,网上的用类绑定这种方法还是太麻烦,也达不到我想要的那种全部能一起打开的效果,所以我就利用refs去获取这个元素的style,然后增加样式,来达到动画效果
当你想打开的时候,你给ul加上
max-height: 600px;
-webkit-transition: max-height .3s;
transition: max-height .3s
当你想关闭的时候,你就给ul加上
max-height: '';
transition: max-height .3s
这样就可以了
至于为什么用this.$refs[n].style.maxHeight===’'这个来判断呢,是因为你一开始设置max-height为0的时候,你用ref去获取得到的为空,你只需要判断你点的这个元素的max-height是否为空,是的话,就加样式,不是的话,就减去样式就可以,当然用jq来做最简单,直接加上类,但是在vue里面还是没这种方法,有什么更好的办法可以留言告诉我。