Basic usage of routing in VUE

route

  1. Understanding: a route is a set of key - value s. Multiple routes need to be managed by a router.
  2. Front end Routing: key is the path and value is the component.

1. Basic use

  1. Install Vue router, command: NPM I Vue router

  2. Application plug-in: Vue.use(VueRouter)

  3. Write router configuration items:

    //Introducing VueRouter
    import VueRouter from 'vue-router'
    //Introducing Luyou components
    import About from '../components/About'
    import Home from '../components/Home'
    
    //Create a router instance object to manage groups of routing rules
    const router = new VueRouter({
    	routes:[
    		{
    			path:'/about',
    			component:About
    		},
    		{
    			path:'/home',
    			component:Home
    		}
    	]
    })
    
    //Exposure router
    export default router
    
  4. Achieve switching (active class configurable highlight style)

    <router-link active-class="active" to="/about">About</router-link>
    
  5. Specify display location

    <router-view></router-view>
    

2. Several points for attention

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

3. Multi level routing (multi-level routing)

  1. 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', //Be sure not to write: / news here
    				component:News
    			},
    			{
    				path:'message',//Do not write: / message here
    				component:Message
    			}
    		]
    	}
    ]
    
  2. Jump (to write the full path):

    <router-link to="/home/news">News</router-link>
    

4. query parameters of route

  1. Transfer parameters

    <!-- Jump and carry query Parameters, to String writing -->
    <router-link :to="/home/message/detail?id=666&title=Hello">Jump</router-link>
    				
    <!-- Jump and carry query Parameters, to Object writing of -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		   id:666,
                title:'Hello'
    		}
    	}"
    >Jump</router-link>
    
  2. Receiving parameters:

    $route.query.id
    $route.query.title
    

5. Named route

  1. Function: it can simplify the jump of routing.

  2. How to use

    1. Name the route:

      {
      	path:'/demo',
      	component:Demo,
      	children:[
      		{
      			path:'test',
      			component:Test,
      			children:[
      				{
                            name:'hello' //Name the route
      					path:'welcome',
      					component:Hello,
      				}
      			]
      		}
      	]
      }
      
    2. Simplified jump:

      <!--Before simplification, you need to write a 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 fit transfer parameters -->
      <router-link 
      	:to="{
      		name:'hello',
      		query:{
      		   id:666,
                  title:'Hello'
      		}
      	}"
      >Jump</router-link>
      

6. params parameters of route

  1. Configure the route and declare to receive params parameters

    {
    	path:'/home',
    	component:Home,
    	children:[
    		{
    			path:'news',
    			component:News
    		},
    		{
    			component:Message,
    			children:[
    				{
    					name:'xiangqing',
    					path:'detail/:id/:title', //Receive params parameters using placeholder declarations
    					component:Detail
    				}
    			]
    		}
    	]
    }
    
  2. Transfer parameters

    <!-- Jump and carry params Parameters, to String writing -->
    <router-link :to="/home/message/detail/666/Hello">Jump</router-link>
    				
    <!-- Jump and carry params Parameters, to Object writing of -->
    <router-link 
    	:to="{
    		name:'xiangqing',
    		params:{
    		   id:666,
                title:'Hello'
    		}
    	}"
    >Jump</router-link>
    

    Special note: when the route carries params parameters, if the object writing method of to is used, the path configuration item cannot be used, but the name configuration must be used!

  3. Receiving parameters:

    $route.params.id
    $route.params.title
    

7. props configuration of routing

Function: make it easier for routing components to receive parameters
{
	name:'xiangqing',
	path:'detail/:id',
	component:Detail,

	//The first way to write it: 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 method: if props value is Boolean and Boolean value is true, all params parameters received by the route will be passed to Detail component through props
	// props:true
	
	//The third way to write: props value is a function, and each group of key values in the object returned by this function will be passed to the Detail component through props
	props(route){
		return {
			id:route.query.id,
			title:route.query.title
		}
	}
}

8. replace attribute of < router link >

  1. Function: control the mode of operating browser history during route jump
  2. There are two ways to write browser history: push and replace. Push is to add history and replace is to replace the current record. The default value for route jump is push
  3. How to start the replace mode: < router link replace... > News < / router link >

9. Program route navigation

  1. Function: route jump is realized without the help of < router link >, making route jump more flexible

  2. Specific code:

    //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() //forward
    this.$router.back() //back off
    this.$router.go() //You can move forward or backward
    

10. Cache routing component

  1. Function: keep the routing components not displayed mounted and not destroyed.

  2. Specific code:

    <keep-alive include="News"> 
        <router-view></router-view>
    </keep-alive>
    

11. Two new life cycle hooks

  1. Function: the two hooks unique to the routing component are used to capture the activation status of the routing component.
  2. Specific name:
    1. Triggered when the activated routing component is activated.
    2. Triggered when the deactivated routing component is deactivated.

12. Route guard

  1. Function: to control the routing permission

  2. Classification: Global guard, exclusive guard and in component guard

  3. Global guard:

    //Global front guard: executed during initialization and before each route switching
    router.beforeEach((to,from,next)=>{
    	console.log('beforeEach',to,from)
    	if(to.meta.isAuth){ //Judge whether the current route needs permission control
    		if(localStorage.getItem('school') === 'atguigu'){ //Specific rules for permission control
    			next() //Release
    		}else{
    			alert('No permission to view')
    			// next({name:'guanyu'})
    		}
    	}else{
    		next() //Release
    	}
    })
    
    //Global post guard: executed during initialization and after each route 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'
    	}
    })
    
  4. Exclusive guard:

    beforeEnter(to,from,next){
    	console.log('beforeEnter',to,from)
    	if(to.meta.isAuth){ //Judge whether the current route needs permission control
    		if(localStorage.getItem('school') === 'atguigu'){
    			next()
    		}else{
    			alert('No permission to view')
    			// next({name:'guanyu'})
    		}
    	}else{
    		next()
    	}
    }
    
  5. Guard inside the assembly:

    //Entry guard: called when entering the component through routing rules
    beforeRouteEnter (to, from, next) {
    },
    //Leave guard: it is called when leaving the component through routing rules
    beforeRouteLeave (to, from, next) {
    }
    

13. Two working modes of router

  1. What is a hash value for a url? --# And what follows is the hash value.

  2. The hash value will not be included in the HTTP request, that is, the hash value will not be brought to the server.

  3. hash mode:

    1. The address always carries a # number, which is not beautiful.
    2. 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.
    3. Good compatibility.
  4. history mode:

    1. The address is clean and beautiful.
    2. Compatibility is slightly worse than hash mode.
    3. When the application is deployed online, it needs the support of back-end personnel to solve the problem of refreshing the page server 404.

Added by MarkB423 on Fri, 05 Nov 2021 06:19:36 +0200