Introduction and usage of router in vue

routing

image

  1. Understanding: A route is a set of mapping relationships (key-value), and multiple routes need to be managed by a router.
  2. Front-end routing: the key is the path, and the value is the component.

1. Basic use

  1. Install vue-router, command:npm i vue-router

  2. Apply plugin:Vue.use(VueRouter)

  3. Write router configuration items:

    //引入VueRouter
    import VueRouter from 'vue-router'
    //引入Luyou 组件
    import About from '../components/About'
    import Home from '../components/Home'
    
    //创建router实例对象,去管理一组一组的路由规则
    const router = new VueRouter({
          
          
    	routes:[
    		{
          
          
    			path:'/about',
    			component:About
    		},
    		{
          
          
    			path:'/home',
    			component:Home
    		}
    	]
    })
    
    //暴露router
    export default router
    
  4. Implement switching (active-class can configure highlighting style)

    <router-link active-class="active" to="/about">About</router-link>
    
  5. target placements

    <router-view></router-view>
    

2. A few points for attention

  1. Routing components are usually stored in pagesfolders, and general components are usually stored in componentsfolders.
  2. By switching, the "hidden" routing components are destroyed by default, and then mounted when needed.
  3. Each component has its own $routeproperties, which store its own routing information.
  4. The entire application has only one router, which can $routerbe obtained through the properties 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:[ //通过children配置子级路由
    			{
          
          
    				path:'news', //此处一定不要写:/news
    				component:News
    			},
    			{
          
          
    				path:'message',//此处一定不要写:/message
    				component:Message
    			}
    		]
    	}
    ]
    
  2. Jump (to write the full path):

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

4. The query parameter of the route

  1. pass parameters

    <!-- 跳转并携带query参数,to的字符串写法 -->
    <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
    				
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		   id:666,
                title:'你好'
    		}
    	}"
    >跳转</router-link>
    
  2. Receive parameters:

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

5. Naming Routes

  1. Function: It can simplify the routing jump.

  2. how to use

    1. Give the route a name:

      {
              
              
      	path:'/demo',
      	component:Demo,
      	children:[
      		{
              
              
      			path:'test',
      			component:Test,
      			children:[
      				{
              
              
                            name:'hello' //给路由命名
      					path:'welcome',
      					component:Hello,
      				}
      			]
      		}
      	]
      }
      
    2. Simplified jump:

      <!--简化前,需要写完整的路径 -->
      <router-link to="/demo/test/welcome">跳转</router-link>
      
      <!--简化后,直接通过名字跳转 -->
      <router-link :to="{name:'hello'}">跳转</router-link>
      
      <!--简化写法配合传递参数 -->
      <router-link 
      	:to="{
      		name:'hello',
      		query:{
      		   id:666,
                  title:'你好'
      		}
      	}"
      >跳转</router-link>
      

6. The params parameter of the route

  1. 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', //使用占位符声明接收params参数
    					component:Detail
    				}
    			]
    		}
    	]
    }
    
  2. pass parameters

    <!-- 跳转并携带params参数,to的字符串写法 -->
    <router-link :to="/home/message/detail/666/你好">跳转</router-link>
    				
    <!-- 跳转并携带params参数,to的对象写法 -->
    <router-link 
    	:to="{
    		name:'xiangqing',
    		params:{
    		   id:666,
                title:'你好'
    		}
    	}"
    >跳转</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!

  3. Receive parameters:

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

7. Routing props configuration

​ Role: Make it easier for routing components to receive parameters

{
    
    
	name:'xiangqing',
	path:'detail/:id',
	component:Detail,

	//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
	// props:{a:900}

	//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
	// props:true
	
	//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
	props(route){
    
    
		return {
    
    
			id:route.query.id,
			title:route.query.title
		}
	}
}

8. <router-link>The replace attribute

  1. Role: control the mode of operating browser history when routing jumps
  2. There are two ways to write the history of the browser: pushand respectively replace, pushwhich is to append the history record, and replaceis to replace the current record. When the route jumps, the default ispush
  3. How to turn on replacethe mode:<router-link replace .......>News</router-link>

9. Programmatic Routing Navigation

  1. <router-link> Function: Make routing jumps more flexible without the help of routing jumps

  2. Specific encoding:

    //$router的两个API
    this.$router.push({
          
          
    	name:'xiangqing',
    		params:{
          
          
    			id:xxx,
    			title:xxx
    		}
    })
    
    this.$router.replace({
          
          
    	name:'xiangqing',
    		params:{
          
          
    			id:xxx,
    			title:xxx
    		}
    })
    this.$router.forward() //前进
    this.$router.back() //后退
    this.$router.go() //可前进也可后退
    

10. Cache Routing Components

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

  2. Specific encoding:

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

11. Two new lifecycle hooks

  1. Function: Two hooks unique to routing components, used to capture the activation status of routing components.
  2. specific name:
    1. activatedFired when the routing component is activated.
    2. deactivatedTriggered when the routing component is deactivated.

12. Route Guard

  1. Role: to control the authority of the route

  2. Category: global guard, exclusive guard, component guard

  3. Global Guard:

    //全局前置守卫:初始化时执行、每次路由切换前执行
    router.beforeEach((to,from,next)=>{
          
          
    	console.log('beforeEach',to,from)
    	if(to.meta.isAuth){
          
           //判断当前路由是否需要进行权限控制
    		if(localStorage.getItem('school') === 'atguigu'){
          
           //权限控制的具体规则
    			next() //放行
    		}else{
          
          
    			alert('暂无权限查看')
    			// next({name:'guanyu'})
    		}
    	}else{
          
          
    		next() //放行
    	}
    })
    
    //全局后置守卫:初始化时执行、每次路由切换后执行
    router.afterEach((to,from)=>{
          
          
    	console.log('afterEach',to,from)
    	if(to.meta.title){
          
           
    		document.title = to.meta.title //修改网页的title
    	}else{
          
          
    		document.title = 'vue_test'
    	}
    })
    
  4. Exclusive Guard:

    beforeEnter(to,from,next){
          
          
    	console.log('beforeEnter',to,from)
    	if(to.meta.isAuth){
          
           //判断当前路由是否需要进行权限控制
    		if(localStorage.getItem('school') === 'atguigu'){
          
          
    			next()
    		}else{
          
          
    			alert('暂无权限查看')
    			// next({name:'guanyu'})
    		}
    	}else{
          
          
    		next()
    	}
    }
    
  5. Guards inside the component:

    //进入守卫:通过路由规则,进入该组件时被调用
    beforeRouteEnter (to, from, next) {
          
          
    },
    //离开守卫:通过路由规则,离开该组件时被调用
    beforeRouteLeave (to, from, next) {
          
          
    }
    

13. Two working modes of the router

  1. For a url, what is the hash value? —— # and the content after it 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. There is always a # sign in the address, 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. Compatibility is better.
  4. history mode:
    1. The address is clean and beautiful.
    2. Compatibility is slightly worse than hash mode.
    3. 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.

©Excerpted from a full set of Vue2.0+Vue3.0 tutorials by Zhang Tianyu of Shang Silicon Valley丨Routing courseware

Guess you like

Origin blog.csdn.net/weixin_48138187/article/details/129037095