Blog>
Snippets

Slide Transition for a Sidebar

An example of animating a sidebar with a slide-in and slide-out effect, using Vue's <Transition> component to enhance user interface navigation.
<template>
  <div>
    <!-- Sidebar toggle button -->
    <button @click="toggleSidebar">Toggle Sidebar</button>

    <!-- Sidebar with slide transition -->
    <transition
      enter-active-class="slide-in"
      leave-active-class="slide-out"
    >
      <aside v-if="isSidebarVisible" class="sidebar">
        <!-- Sidebar content goes here -->
      </aside>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isSidebarVisible: false, // Sidebar visibility state
    };
  },
  methods: {
    toggleSidebar() {
      this.isSidebarVisible = !this.isSidebarVisible;
    }
  }
};
</script>

<style scoped>
/* Keyframes for slide-in effect */
@keyframes slideIn {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0);
  }
}

/* Keyframes for slide-out effect */
@keyframes slideOut {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}

.slide-in {
  animation: slideIn .3s ease-out forwards;
}

.slide-out {
  animation: slideOut .3s ease-out forwards;
}

.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  /* Other styles for your sidebar (width, height, etc.) */
}
</style>
This Vue component example includes a template for the sidebar and its toggle button, a script section handling the sidebar visibility state, and scoped CSS animations for the slide-in and slide-out effects. The enter-active-class and leave-active-class on the <transition> tag specify the CSS classes to apply when the sidebar enters or leaves, corresponding to the .slide-in and .slide-out classes defined in the <style> tag. The scoped CSS includes keyframes for both the slide-in and slide-out animations, which move the sidebar on and off-screen with a translation transform.