使用vue编写一个通用的多级菜单组件子菜单展开时需要有过渡效果
以下是一个使用Vue编写的通用多级菜单组件,其中子菜单展开时使用了过渡效果:
<template>
<ul>
<li v-for="(item, index) in menuItems" :key="index">
<a @click="toggleSubMenu(item)">
{{ item.name }}
<span v-if="item.children" :class="{'rotate-arrow': item.showSubMenu}">▾</span>
</a>
<transition name="slide-down">
<menu v-if="item.children && item.showSubMenu" :menu-items="item.children"></menu>
</transition>
</li>
</ul>
</template>
<script>
export default {
name: 'Menu',
props: {
menuItems: {
type: Array,
required: true
}
},
data() {
return {
activeIndex: null
}
},
methods: {
toggleSubMenu(item) {
if (item.children) {
item.showSubMenu = !item.showSubMenu
}
}
}
}
</script>
<style scoped>
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
margin: 0;
padding: 0;
}
a {
display: block;
padding: 10px;
color: #333;
text-decoration: none;
}
.rotate-arrow {
transform: rotate(90deg);
}
.slide-down-enter-active {
transition: all 0.3s ease-out;
}
.slide-down-leave-active {
transition: all 0.3s ease-out;
}
.slide-down-enter,
.slide-down-leave-to {
height: 0;
opacity: 0;
}
</style>
上述代码中,我们使用了Vue的过渡组件<transition>来为子菜单添加展开/收起的动画效果。我们使用了slide-down作为过渡动画的名称,并在样式中定义了该动画的具体效果。当子菜单展开时,其高度和透明度会从0渐变到最终的值,而当子菜单收起时,其高度和透明度会从最终的值渐变到0。
原文地址: https://www.cveoy.top/t/topic/bMYC 著作权归作者所有。请勿转载和采集!