我有一个侧边栏组件,它利用过渡元素在侧边栏隐藏和显示时将其滑入和滑出。关闭时它会滑出,但只要打开它,它就会弹出。
侧边栏.vue
<template>
<aside v-if="mountSidebar" class="min-h-screen">
<transition name="slide" appear @after-leave="close()">
<div v-show="closeSidebar" class="min-h-screen" :class="`bg-${bgColor}`">
<slot></slot>
</div>
</transition>
</aside>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue";
export default defineComponent({
name: "Sidebar",
props: {
bgColor: {
type: String,
default: "blue",
},
textColor: {
type: String,
default: "white",
},
modelValue: {
type: Boolean,
default: true,
},
},
emits: ["update:modelValue"],
setup(props, { emit }) {
const mountSidebar = ref(props.modelValue);
const closeSidebar = ref(props.modelValue);
const close = () => {
emit("update:modelValue", false);
mountSidebar.value = props.modelValue;
};
watch(
() => props.modelValue,
(value) => {
if (value) mountSidebar.value = true;
closeSidebar.value = value;
}
);
return {
close,
mountSidebar,
closeSidebar,
};
},
});
</script>
<style>
.slide-enter-active,
.slide-leave-active {
transition: transform 0.2s ease;
}
.slide-enter,
.slide-leave-to {
transform: translateX(-100%);
transition: all 150ms ease-in 0s;
}
</style>
然后我的 App.vue 只有一个按钮,用于切换设置为侧边栏上的 modelValue 道具的值,即<sidebar showSidebar ...>content</sidebar>