Vue Router was recently used in writing Vue version bookkeeping projects. It is through managing URL, realize component switch and state change. Make a note of some of the features used in the project.
The installation
npm install vue-router
Copy the code
Basic usage
- Use the routing functionality explicitly installed via vue.use (VueRouter) in modular projects:
- Map components to routes and tell the Vue Router where to render them.
For example, make a navigation bar that has two pages handled by the router: a home page and a user page. When different links are clicked, the router displays the corresponding page.
// index.ts: import Vue from "vue"; import VueRouter from "vue-router"; import Detail from "@/views/Detail.vue"; import Account from "@/views/Account.vue"; import NotFound from "@/views/NotFound.vue"; Vue.use(VueRouter); Const routes = [// default to Account component {path: "/", Component: Account}, {path: "/ Account ", component: }, // Render NotFound component {path: "*", Component: NotFound},]; const router = new VueRouter({ routes }); export default router;Copy the code
// App.vue
<template>
<div id="app" >
<router-view/>
</div>
</template>
Copy the code
redirect
- Do this with the Routes configuration, redirecting from/to /account:
{
path: "/",
redirect: "/account",
},
Copy the code
router-link
- Use the router-link component to navigate
- By passing in
to
Attribute specified link - The router-link tag is rendered as an A tag by default
- If a router-link route is successfully matched, the selected class indicates that the route is activated
This.$route.params.id <router-link to="/detail" active-class="selected">Copy the code
this.$router
和 this.$route
- By injecting the router, we can pass through any component
this.$router
To access the router, you can also passthis.$route
To access the current route: - This.$router.back() returns to the previous page
- This.$router.push(‘/’) locates the page corresponding to the default route
- This.$route.params.id gets the parameter
Route component parameters are transmitted
- Add the routing
{
path: "/record/:id",
component: Record
}
Copy the code
- Navigate specified components
<router-link :to=" '/record/${xx}' "> Jump to record component </router-link>Copy the code