[vue-router] dynamic routing, nested routing, guards and programmatic navigation

Table of contents

1. Programmatic navigation

⭕️The way to realize page jump

⭕️The way of parameter passing

example

2. Nested routing

3. Dynamic route matching

4. Navigation Guard 

1. Global Guard

Global Front Guard

global rear guard

2. Routing Exclusive Guard

3. Guard within the component

5. The method of monitoring changes in the routing url address bar

6. Routing mode 


1. Programmatic navigation

Programmatic navigation is used for page jumps.

The way to use <router-link>the create a tag to define navigation links to achieve routing jumps is called declarative navigation .

Programmatic navigation is implemented by writing codes with the help of instance methods of router.

⭕️The way to realize page jump

1、$router.push

Using $router.push() to jump to the specified route will add a new record to the history stack. When the user clicks the back button of the browser, they can return to the url before the jump.

this.$router.push({
  path:'/aDetails',
  query:{id}
})

2、$router.replace

Using $router.replace will not add history to the browser

this.$router.replace({
  path:"/aDetails",
  query:{id}
})

3、$router.go

$router.go is used to jump to the specified page, either forward or backward

//前进一步记录
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 不传递参数或者参数为 0,表示刷新当前页面
router.go()
// 如果 history 记录不够用,则会报错
router.go(-100)
router.go(100)

4. Use the <router-link> tag (essentially a tag)

5. Use the a tag

⭕️The way of parameter passing

1. path-query parameter passing

this.$router.push({
  path:'/aDetails',
  query:{id}
})

When passing parameters by combining path and query, the parameters will be spliced ​​in the address bar of the browser, and the data will not be lost after refreshing the page.  

2. Name-params pass parameters

this.$router.push({
  name:"ADetails",
  params:{id},
})

When using the parameters passed by the combination of name and params, the parameters are carried in $route, and the passed parameters are one-time, and the data will be lost when the page is refreshed. 

example

Write a small case:
click on the article title to jump to the article details page (written in vue-cli)

Create two components under components: Article.vue and ArticleDetails.vue

Configure routing in index.js under router:
 

  app.vue

  

Item.view

ArticleDetails.vue 

 The result printed by this.$route:

 The result of the operation is as follows: 

It can be seen that using query to pass parameters, the parameters are carried on the address bar. 

2. Nested routing

The application interface in real life is usually composed of multi-layer nested components. Similarly, each segment of the dynamic path in the URL also corresponds to each layer of nested components in a certain structure.

example:

Create three components under components: AboutOne.vue, AboutTwo.vue, AboutThree.vue

 AboutOne.vue

<template>
  <div>
    about-one
  </div>
</template>

AboutTwo.vue

<template>
  <div>
    about-two
  </div>
</template>

AboutThree.vue

<template>
  <div>
    about-three
  </div>
</template>

Configure routing in index.js under router:

 AboutView.vue under views

<template>
  <div class="about">
    <div><router-link to='aboutone'>about1</router-link></div>
    <div><router-link to='abouttwo'>about2</router-link></div>
    <div><router-link to='aboutthree'>about3</router-link></div>
    <div>
      <router-view></router-view>
    </div>  
  </div>
</template>

 

3. Dynamic route matching

We often need to map all routes matched by a certain pattern to the same component.

For example: there is a user component, and all users with different ids must use this component to render, then you can use dynamic path parameters in the routing path of vue-router to achieve this effect. Dynamic path parameters are identified with a colon.

index.js 

app.vue 

 

It can be seen that when we change the dynamic path parameter, the page does not jump, and it is still the current page.

4. Navigation Guard 

Navigation guards are triggered when the route changes. Navigation guards are divided into global guards, routing exclusive guards and component guards.

1. Global Guard

Global Front Guard

beforeEach((to,from,next)=>{
  next();//手动调用向下执行
  next(fale);//阻止路由向下执行				
})

Parameter Description:

to: the target route that is about to enter has an object
from: the route that the current navigation is about to leave
next: is a function, which must be called to execute this hook. The execution effect depends on the call parameter of the next method. The parameter defaults to true, which means downward execution, and false, which means to prevent the route from executing downward.

global rear guard

The global rear guard has no next method, it does not need to call the next method to let the route execute downward

afterEach((to,from)=>{

})

2. Routing Exclusive Guard

Route exclusive guard needs to enter the current route to trigger.

beforeEnter((to,from,next)=>{

})

3. Guard within the component

//进入组件路由时触发
beforeRouteEnter(to,from,next){};
//组件路由更新时触发
beforeRouteUpdate(to,from,next){};
//离开组件路由时触发
beforeRouteLeave(to,from,next){};

This in beforeRouteEnter points to window,

This in beforeRouteUpdate and beforeRouteLeave points to the component instance.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.5.4/vue-router.min.js"
		integrity="sha512-zxWuRslhjyZyRAYInXTNl4vC/vBBwLQuodFnPmvYAEvlv9XCCfi1R3KqBCsT6f9rk56OetG/7KS9dOfINL1KCQ=="
		crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
	<div id="app">
		<!-- 使用路由 to表示要去的路由-->
		<router-link to="/article">去文章管理</router-link>
		<router-link to="/column">去栏目管理</router-link>
		<router-link to="/user/1">用户管理</router-link>
		<!-- 路由出口 匹配路由对应的组件 -->
		<router-view></router-view>
	</div>
	<script>
    // 组件article
		let article = {
			template: `
				<div>文章页面</div>
			`,
		};
    // 组件user 
		let user = {
            template: `
				<div>用户页面---{
   
   {id}}</div>
			`,
			// 4、组件内守卫
			beforeRouteEnter(to, from, next) {
				console.log(this, 'beforeRouteEnter');
				console.log(to, from);
				next()
			},
			beforeRouteUpdate(to, from, next) {
				console.log(this, 'beforeRouteUpdate');
			},
			beforeRouteLeave(to, from, next) {
				console.log(this, 'beforeRouteLeave');
				next()
			},
			data() {
				return {
					id: 0
				}
			},
		};
    // 组件column
		let column = {
			template: `
				<div>栏目页面</div>
			`
		};
		// 配置路由对象数组
		let routes = [
			{
				path: '/article',
				component: article
			},
			{
				path: '/column',
				component: column,
				// 3、路由独享守卫 只有进入当前路由时才会触发
				beforeEnter: (to, from, next) => {
					console.log(to,from,next);
					next();
				}
			},
			{
				path: '/user/:id',
				component: user
			}
		];
		// 创建路由器对象router
		let router = new VueRouter({
			routes,
		});
		
    // 1、全局前置守卫
		router.beforeEach((to,from,next)=>{
			console.log(to,from,next);
			next()
		  // next(false);//阻断路由向下执行
		});
		// 2、全局后置守卫 
		router.afterEach((to,from)=>{
			console.log(to,from);
		})
		new Vue({
			router,
			el: "#app",
			data: {

			}
		})
	</script>
</body>

</html>

5. The method of monitoring changes in the routing url address bar

1. Listen in created

created(){
  console.log(this.$route.params.xxx)
}

2. Use watch to monitor

watch:{
  $route(to,from){
    //to ---即将进入的路由
    //from --上一个离开的路由
    console.log(to.params)
  }
}

3. Use the guard in the component to monitor (the hook that will be triggered when the component is updated)

beforeRouteUpdate(to,from,next){
  console.log(to.params)
  next()
}

By monitoring changes in the address bar, the parameters carried in the address bar can be obtained. 

6. Routing mode 

Routing modes include hash mode and history mode, and the default is hash mode.

The routing mode is set in the router object:

let router = new VueRouter({
    routes,
	// 路由模式
	mode: 'history'
	// mode: 'hash'
});

The working principle of the hash mode is the hashchange event, which can monitor the change of the hash in the window. We randomly add a #xx after the url to trigger this event.

window.onhashchange = function (event) {
	console.log(event);
}

Print out a HashChangeEvent event object, in which there are newURL and oldURL  

Print out the window.history object, there are back(), forword(), go() and other methods in the history object:

The difference between the two:
1. hash will carry # in the routing path, history will not carry # in the routing path
2, hash refresh page will not request the server, history refresh page will request the server
3, the working principle of hash is the hashchange event
4, The working principle of history is to use go, back, forward
5, and hash to support low-version browsers. History is a new API for h5

Guess you like

Origin blog.csdn.net/lq313131/article/details/127115406