Vue study notes | routing

Basic concepts of routing

  • Understanding: A route is a set of mapping relationships (key-value), and multiple routes need to be managed by a router.

  • Front-end routing: the key is the path, and the value is the component.

  • vue-router: A plug-in library for vue, specially used to implement SPA applications

  • Understanding of SPA applications

    • single page web application (SPA)

    • There is only one full page for the entire application

    • Clicking the navigation link in the page will not refresh the page, only a partial update of the page

    • Data needs to be obtained through ajax request

  • A route is a set of mapping relationships (key-value)

  • key is path, value may be function or component

  • routing classification

    • Backend routing:

      • Understanding: value is a function, which is used to process the request submitted by the client.

      • Working process: When the server receives a request, it finds a matching function according to the request path to process the request and returns the response data.

    • Front-end routing:

      • Understanding: value is a component used to display page content.

      • Working process: When the path of the browser changes, the corresponding component will be displayed

basic use

  • Install vue-router, command: npm i vue-router

vue-router3 is used in vue2; vue-router4 is used in vue3

npm i vue-router@3

  • Application plugin: Vue.use(VueRouter)
  • Write router configuration items:
//Introducing VueRouter
import VueRouter from 'vue-router'
//Import Luyou component
import About from '../components/About'
import Home from '../components/Home'

//Create a router instance object to manage a group of routing rules
const router = new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home
		}
	]
})

//expose router
export default router
  • Implement switching (active-class can configure highlighting style)
<router-link active-class="active" to="/about">About</router-link>
  • target placements
<router-view></router-view>

A few points of attention

  1. Routing components are usually stored in the pages folder, and general components are usually stored in the components folder.
  2. By switching, the "hidden" routing components are destroyed by default, and then mounted when needed.
  3. Each component has its own $route property, which stores its own routing information.
  4. The entire application has only one router, which can be obtained through the $router property of the component.

Multi-level routing (nested routing)

  • To configure routing rules, use the children configuration item:
routes:[
	{
		path:'/about',
		component:About,
	},
	{
		path:'/home',
		component:Home,
		children:[ //Configure child routing through children
			{
				path:'news', //Do not write here: /news
				component:News
			},
			{
				path:'message',//Do not write here: /message
				component:Message
			}
		]
	}
]
  • Jump (to write the full path):
<router-link to="/home/news">News</router-link>

The query parameter of the route

  • pass parameters
<!-- jump and carry query parameter, to The string writing method of -->
<router-link :to="/home/message/detail?id=666&title=Hello">jump</router-link>
				
<!-- jump and carry query parameter, to object writing -->
<router-link 
	:to="{
		path:'/home/message/detail',
		query:{
		   id:666,
            title:'Hello'
		}
	}"
>jump</router-link>
  • Receive parameters:
$route.query.id
$route.query.title

named route

  • Function: It can simplify the routing jump.

  • how to use

    • Give the route a name:
{
	path:'/demo',
	component:Demo,
	children:[
		{
			path:'test',
			component:Test,
			children:[
				{
                      name:'hello' //name the route
					path:'welcome',
					component:Hello,
				}
			]
		}
	]
}
  • Simplified jump:
<!--Before simplifying, you need to write the complete path -->
<router-link to="/demo/test/welcome">jump</router-link>

<!--After simplification, jump directly through the name -->
<router-link :to="{name:'hello'}">jump</router-link>

<!--Simplified writing and passing parameters -->
<router-link 
	:to="{
		name:'hello',
		query:{
		   id:666,
            title:'Hello'
		}
	}"
>jump</router-link>

The params parameter of the route

  • Configure routing, declare to receive params parameters
{
	path:'/home',
	component:Home,
	children:[
		{
			path:'news',
			component:News
		},
		{
			component:Message,
			children:[
				{
					name:'xiangqing',
					path:'detail/:id/:title', //Use placeholder declarations to receive params parameters
					component:Detail
				}
			]
		}
	]
}
  • pass parameters
<!-- jump and carry params parameter, to The string writing method of -->
<router-link :to="/home/message/detail/666/Hello">jump</router-link>
				
<!-- jump and carry params parameter, to object writing -->
<router-link 
	:to="{
		name:'xiangqing',
		params:{
		   id:666,
            title:'Hello'
		}
	}"
>jump</router-link>

Special attention: When the route carries params parameters, if you use the object writing method of to, you cannot use the path configuration item, you must use the name configuration!

  • Receive parameters:
$route.params.id
$route.params.title

Routing props configuration

  • ​ Role: Make it easier for routing components to receive parameters
{
	name:'xiangqing',
	path:'detail/:id',
	component:Detail,

	//The first way of writing: the props value is an object, and all key-value combinations in the object will eventually be passed to the Detail component through props
	// props:{a:900}

	//The second way of writing: the props value is a Boolean value, and the Boolean value is true, then all the params parameters received by the route are passed to the Detail component through props
	// props:true
	
	//The third way of writing: the props value is a function, and each set of key-value s ​​in the object returned by the function will be passed to the Detail component through props
	props(route){
		return {
			id:route.query.id,
			title:route.query.title
		}
	}
}

replace attribute of <router-link>

  • Role: control the mode of operating browser history when routing jumps
  • There are two ways to write browser history records: push and replace respectively, push is to add history records, and replace is to replace current records. The default is push when routing jumps
  • How to enable replace mode: <router-link replace ......>News</router-link>

Programmatic Routing Navigation

  • Function: Realize routing jump without using <router-link>, making routing jump more flexible
  • Specific encoding:
//Two API s of $router
this.$router.push({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx
		}
})

this.$router.replace({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx
		}
})
this.$router.forward() //go ahead
this.$router.back() //step back
this.$router.go() //Can go forward or backward

Cache Routing Components

  • Function: keep the routing components that are not displayed mounted and not destroyed.
  • Specific encoding:
<keep-alive include="News"> 
    <router-view></router-view>
</keep-alive>

Two new lifecycle hooks

  • Function: Two hooks unique to routing components, used to capture the activation status of routing components.
  • specific name:
    • activated Triggered when the route component is activated.
    • Triggered when the deactivated routing component is deactivated.

route guard

  • Role: to control the authority of the route
  • Category: global guard, exclusive guard, component guard
  • Global Guard:
//Global front guard: Execute at initialization, before each routing switch
router.beforeEach((to,from,next)=>{
	console.log('beforeEach',to,from)
	if(to.meta.isAuth){ //Determine whether the current route needs permission control
		if(localStorage.getItem('school') === 'atguigu'){ //Specific rules for permission control
			next() //let go
		}else{
			alert('No permission to view')
			// next({name:'guanyu'})
		}
	}else{
		next() //let go
	}
})

//Global post guard: Execute at initialization, after each routing switch
router.afterEach((to,from)=>{
	console.log('afterEach',to,from)
	if(to.meta.title){ 
		document.title = to.meta.title //Modify the title of the page
	}else{
		document.title = 'vue_test'
	}
})
  • Exclusive Guard:
beforeEnter(to,from,next){
	console.log('beforeEnter',to,from)
	if(to.meta.isAuth){ //Determine whether the current route needs permission control
		if(localStorage.getItem('school') === 'atguigu'){
			next()
		}else{
			alert('No permission to view')
			// next({name:'guanyu'})
		}
	}else{
		next()
	}
}
  • Guards inside the component:
//Entry Guard: Called when entering the component through routing rules
beforeRouteEnter (to, from, next) {
},
//Leave Guard: Called when leaving the component through routing rules
beforeRouteLeave (to, from, next) {
}

Two working modes of the router

  • For a url, what is the hash value? —— # and the content after it is the hash value.
  • The hash value will not be included in the HTTP request, that is: the hash value will not be brought to the server.
  • hash mode:
    • There is always a # sign in the address, which is not beautiful.
    • If the address is shared through a third-party mobile app in the future, if the app verification is strict, the address will be marked as illegal.
    • Compatibility is better.
  • history mode:
    • The address is clean and beautiful.
    • Compatibility is slightly worse than hash mode.
    • When the application is deployed and launched, it needs the support of the back-end personnel to solve the problem of refreshing the page server 404.

Tags: Javascript Vue.js Vue

Posted by Huijari on Tue, 03 Jan 2023 18:47:38 +0530