Home > Article > Web Front-end > How to use Router to implement redirection function in Vue project
How to use Router to implement redirection function in Vue project
In a Vue project, we often need to implement jump and redirection functions between pages. Vue Router provides a simple yet powerful solution. This article will introduce how to use Router to implement the redirection function in a Vue project and give specific code examples.
npm install vue-router
or
yarn add vue-router
Vue Router. After the installation is complete, we can proceed to the next step of configuration.
import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', routes: [ // 在这里配置路由 ], }); export default router;
In the above code, we set the Router mode to 'history', which can remove the # symbol in the URL and make the URL more beautiful.
const router = new VueRouter({ mode: 'history', routes: [ { path: '/', redirect: '/home', }, // 其他路由配置 ], });
In the above example, we redirect the page with the path '/' to '/home' . That is, when the user accesses the root path, we will redirect the page to '/home' and display that page instead.
<template> <div> <h1>Home</h1> <button @click="redirectToAbout">Go to About Page</button> </div> </template> <script> export default { methods: { redirectToAbout() { this.$router.push('/about'); }, }, }; </script>
In the above code, we have added a button in the Home component. When the button is clicked, the redirectToAbout method will be called, redirecting the page to '/about' through the $router.push method.
In this way, we successfully implemented the redirection function using Vue Router. Not only that, Vue Router also provides many other functions, such as dynamic routing, routing parameters, etc., which can be used as needed.
Summary
Through the above steps, we can use Vue Router to implement the redirection function in the Vue project. First install and configure Vue Router, then add redirection rules in the routing configuration file, and finally call the $router.push method in the component to redirect. I hope the sample code in this article can help you better understand and use Vue Router.
The above is the detailed content of How to use Router to implement redirection function in Vue project. For more information, please follow other related articles on the PHP Chinese website!