Home> Web Front-end> Vue.js> body text

How to use routing in Vue to achieve transition effects when switching pages?

PHPz
Release: 2023-07-21 20:25:35
Original
1466 people have browsed it

How to use routing in Vue to achieve transition effects when switching pages?

With the development of front-end technology, page switching animation, as an important part of improving user experience, is more and more widely used in Web applications. In the Vue framework, we can implement page switching through routing, and combine it with Vue's transition effect to achieve animation effects when switching pages. This article will introduce how to use Vue's routing and transition effects to achieve the transition effect of page switching.

First, we need to install the Vue routing plug-in. Enter the following command on the command line to install:

npm install vue-router
Copy after login

After installation, introduce Vue and Vue-router into the project's entry file (main.js), and create a Vue-router instance. The code is as follows:

import Vue from 'vue' import VueRouter from 'vue-router' import App from './App.vue' Vue.use(VueRouter) const router = new VueRouter({ routes: [ // 路由配置 ] }) new Vue({ router, render: h => h(App), }).$mount('#app')
Copy after login

Next, we need to configure routing. Create an index.js file under the router folder and configure routing information in it. The following is an example:

import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import About from '../views/About.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
Copy after login

In the process of configuring routing, we can achieve the corresponding relationship between routing and pages by defining path, name and component. For example, in the above code: when accessing the root path, the Home component will be rendered; when accessing the /about path, the About component will be rendered.

Next, we need to use the tag in App.vue to render the component corresponding to the route. The code is as follows:

Copy after login

At this point, we can already switch pages through routing. But if we want to add a transition effect for page switching, then we need to use Vue's transition effect.

In App.vue, we can use Vue's component to add transition effects for page switching. First, wrap a component outside the tag, the code is as follows:

Copy after login

Then, define the .fade style in the