vue3 使用Transition实现一个侧边菜单 电脑版发表于:2024/12/4 16:04 ### 从左边弹出 ``` <template> <div> <button @click="showMenu = !showMenu">打开菜单</button> <transition name="slide"> <div v-if="showMenu" class="side-menu"> <!-- 菜单内容 --> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <div class="side-menu-switch"> <button @click="showMenu = !showMenu">关闭菜单</button> </div> </div> </transition> </div> </template> <script> import { ref } from 'vue' export default { setup() { const showMenu = ref(false) return { showMenu } } } </script> <style> .slide-enter-active, .slide-leave-active { transition: transform 0.3s ease; } .slide-enter-from, .slide-leave-to { transform: translateX(-100%); } .side-menu { width: 200px; height: 100vh; background-color: #3498db; position: fixed; top: 0; left: 0; color: white; padding: 20px; box-sizing: border-box; } .side-menu .side-menu-switch{ position:absolute; right: -80px; top: 100px; } </style> ``` ### 从右边弹出 ``` <template> <div> <button @click="showMenu = !showMenu">打开菜单</button> <transition name="slide"> <div v-if="showMenu" class="side-menu"> <!-- 菜单内容 --> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <div class="side-menu-switch"> <button @click="showMenu = !showMenu">关闭菜单</button> </div> </div> </transition> </div> </template> <script> import { ref } from 'vue' export default { setup() { const showMenu = ref(true) return { showMenu } } } </script> <style> .slide-enter-active, .slide-leave-active { transition: transform 0.3s ease; } .slide-enter-from, .slide-leave-to { transform: translateX(100%); } .side-menu { width: 200px; height: 100vh; background-color: #3498db; position: fixed; top: 0; right: 0; color: white; padding: 20px; box-sizing: border-box; } .side-menu .side-menu-switch{ position:absolute; left: -80px; top: 100px; } </style> ```