Vue-router is used to set the access path and map the path to components in a project. In a single-page application, the change of the page path means the switch of components.
Procedure 1 Install and use vue-router
Install the vue – the router
- Select router when creating vue-CLI
- Run the NPM command
npm install vue-router --save
Using the vue – the router
Step 1: Import the route object and invoke it
import Vue from "vue"; // import VueRouter from "vue-router"; Vue.use(VueRouter);Copy the code
Step 2: Create a routing instance and mount it in the Vue instance (main.js)
Step 3: Create routing components and configure mapping relationships
const Home = () => import(".. /views/home/Home"); const Cart = () => import(".. /views/cart/Cart"); Vue.use(VueRouter); const routes = [ { path: "/home", component: Home }, { path: "/cart", component: Cart }]; const router = new VueRouter({ routes, mode: "history" }); export default router;Copy the code
Step 4: Use the route and pass<router-view></router-view>
or<router-link></router-link>
<router-view>
: This TAB dynamically renders different components based on the current path<router-link>
: This tag is a built-in component of vue-Router and will be rendered as one<a>
The label.
Use in app.vue
2 Small details of using vue-Router
2.1 Default Path The home page is displayed
You can configure an additional path in routes to redirect the new path to the /home path.
const routes = [
{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
}]
Copy the code
2.2 Changing the Path Mode
Run the mode command to change the hash mode of the default path to history
const router = new VueRouter({
routes,
mode: "history"
})
Copy the code
2.3 the router – the link
- To: indicates the pointing path
- Tga: You can change the default a label format to another label
- Replace: Does not leave a history record and cannot return to the previous page using the back key
- Active-class: If the matched route succeeds, a router-link-active class is configured for the current router-link. You can perform CSS operations based on the name of this class
<router-link to="/home" tag="button" replace active-class="active"> home </router-link>
2.4 Dynamic Routing
Different from static routes, dynamic routes can change the route list of a site based on different factors. For example, when we enter the user interface, we want it to be User/Jack or User/Kobe.
Path parameters pass the “:” flag. When a route is matched, the parameter value is set to this.$route.params, which can be used within each component. So we can update the User template to print the ID of the current User:
export default { name: "App", data() { return { id: "zhangsan" }; }};Copy the code
Used in conjunction with V-bind
<router-link :to="'/user/'+id"> user </router-link>Copy the code
Ids can be obtained dynamically
3 lazy loading
3.1 The role of lazy loading
Routing usually defines many different pages, which are usually placed in a SINGLE JS file. When the page content is too large, we request the page from the server, which may take some time, and the user experience is not good.
3.2 Usage of lazy loading
Code analysis combining vUE’s asynchronous components and Webpack
const Home = resolve => { require.ensure(['../components/Home.vue'], () => { resolve(require('.. /components/Home.vue')); }); };Copy the code
AMD writing
const About = resolve => require(['../components/About.vue'], resolve);
Copy the code
ES6 writing
const Home = () => import('.. /components/Home.vue');Copy the code
4 Route nesting
Nested routines are more common, such as accessing a home page through /home/news or /home/message, where a path maps a component and accessing both paths renders each component separately.
Implement route nesting
- Create the corresponding child component
- Configure child routes in the route mapping
{
path: "/home",
component: Home,
children: [
{
path: '',
redirect: 'news'
},
{
path: "news",
component: HomeNews
},
{
path: "message",
component: HomeMessage
}
]
},
Copy the code
- Used within a component
<router-view>
5 Transfer Parameters
Pass some parameters when jumping routes
5.1 Parameter Types:
There are two main types of parameters passed:
- Params type
Set the route format as follows: /router/: Id transmission mode: Set the path after path to the corresponding value: /router/ ABC
- The query type
Configure the route format as follows: /router Transfer mode: Use the Query key as the transfer mode in the object. id=abc
5.2 Transfer Mode
- router-link
"The router - link: to =" {path: '/ profile, query: {name: "according to", the age: 18, height: 1.88}} ">Copy the code
- JS code
App. Vue writes
methods:{
toPro(){
this.$router.push({
path:'/profile/'+abc,
query:{name:'kobe',age:18}
})
}
}
Copy the code
5.3 $router
and$route
$router
Is an instance of vue-router, and navigation to different urls can be done with $router.push$route
Is the current Router jump object and can pass
Route. params and others obtain data
6 Navigation Guard
Vue-router provides navigation guards that are used to guard navigation by jumping or canceling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level. And changes to parameters or queries do not trigger entry/exit navigational guards.
6.1 Used for global Front navigation
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
Copy the code
- To: Route: indicates the destination Route to be entered
- From: Route: indicates the Route that the current navigation is about to leave
- Next: Function: After this method is called, the next hook can be accessed
For example, 6.2
The global navigator can listen for route jumps and change the title of each URL. For example, add a title to each route configuration, and then use the global navigator to change the title of that URL when each route jumps. The implementation is as follows: Add the title attribute
{path: "/user/:id", Component: user, meta: {title: "user"}}, {path: "/profile", Component: profile, meta: {title: "/user/:id", Component: user, meta: {title: "user"}}, {path: "/profile", Component: profile, meta: {title: "File"}}Copy the code
Through the global front navigation
Router. BeforeEach ((to, from, next) => {// Jump from from to document.title = to.matched[0].meta. next(); });Copy the code
6.3 Other Guards
Global guard:
BeforeEach ((to, from, next) => {//... })/rear / 2 global router afterEach ((to and from) = > {/ /... }) //3 Routes exclusive guard: [{path: '/foo', Component: foo, beforeEnter: BeforeRouteEnter (to, from, next) {}, beforeRouteUpdate(to, from, next) => {//...}}] Next) {}, beforeRouteLeave(to, from, next) {Copy the code
7 keep-alive
Keep-alive is a built-in Vue component that can preserve the state of contained components or prevent them from being re-rendered. Router-view is also a component. If a router-view is wrapped in keep-alive, all view components matched by the path are cached.