Vue.js 3.0 Tutorial
Vue.js 3.0 Component Advanced
Vue.js 3.0 Transitions & Animations
Vue.js 3.0 Reusable & Combinable
Vue.js 3.0 Advanced
Vue.js 3.0 Tools
Vue.js 3.0 Scale
Vue.js 3.0 Accessibility
Vue.js 3.0 Migrating from Vue2
Vue.js 3.0 Contribute Documentation
Vue.js 3.0 API References
Vue.js 3.0 Style Guide
In Vue 3.0, you can add enter and exit transitions to your components with the <transition>
element. Vue provides several classes that are automatically applied to elements within <transition>
during their lifecycle.
Here's how to use them:
Step 1: Initialize your Vue project.
Create a new Vue 3 project using the Vue CLI.
npm install -g @vue/cli vue create my-project
Choose Vue 3 when asked which version of Vue to use.
Step 2: In your component, wrap the element you want to apply a transition to within a <transition>
element.
Here's an example:
<template> <div id="app"> <button @click="show = !show"> Toggle </button> <transition name="fade"> <p v-if="show">Hello Vue.js!</p> </transition> </div> </template> <script> export default { data() { return { show: true } } } </script> <style> .fade-enter-active, .fade-leave-active { transition: opacity .5s; } .fade-enter-from, .fade-leave-to { opacity: 0; } </style>
In this example, we use a v-if
directive on a p
element inside the transition
component. When the button is clicked, it toggles the value of show
between true
and false
, causing the p
element to be added and removed from the DOM.
We also define the name of the transition as "fade". Vue will use this name to automatically apply classes during the transition.
Step 3: Define the styles for the transition in your CSS. Vue automatically applies certain classes at different stages of the transition.
In this example, we define styles for the following classes:
.fade-enter-active
and .fade-leave-active
: These classes are present during the entire enter and leave phases. Here we add a half second opacity transition..fade-enter-from
and .fade-leave-to
: These classes are present at the start of the enter transition and at the end of the leave transition. Here we set the opacity to 0.Step 4: Run your application.
You can run your Vue 3 application with the following command:
npm run serve
Now, when you click the "Toggle" button, the p
element should smoothly fade in and out.
This is a basic introduction to Vue 3 transitions. Vue provides many more transition classes for more control over your transitions, including separate transitions for enter and leave, transitions for list elements, and JavaScript hooks for programmatically controlling your transitions.