Vue learning 117~133 (routing)

5.1 Related understanding

5.1.1 Understanding vue-router

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

5.1.2 Understanding of SPA applications.

  1. Single page web application (SPA).
  2. The entire application only一个完整的页面.
  3. Click the navigation link in the page不会刷新 page, only the page will be created局部更新.
  4. Data needs to be obtained through ajax request.

5.1.3 Understanding routing

  1. What is routing?
  • A route is a set of mapping relationships (key - value)
  • key is the path, value may be function or component
  1. Route classification

Backend routing:

  • Understanding: value is a function, used to process requests submitted by the client.
  • Working process: When the server receives a request, it finds the matching function according to the request path to process the request and return the response data.

Front-end routing:

  • Understanding: value is a component, used to display page content.
  • Working process: When the browser path changes, the corresponding component will be displayed.

5.2 Basic use

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

After February 7, 2022, the default version of vue-router will be version 4. vue-router4 can only be used in vue3.

vue-router3才能在vue2中使用

  1. Apply plugin:Vue.use(VueRouter)

  2. 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
    
  3. Implement switching (active-class can configure highlight style)

    <router-link active-class="active" to="/about">About</router-link>
    
  4. Target placements

    <router-view></router-view>
    

5.3 Several points to note

  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 can be mounted again when needed.
  3. Each component has its own$route attribute, which stores its own routing information.
  4. There is only one router in the entire application, which can be obtained through the component's $router attribute.

5.4 Nested 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 (please write the complete path):

    <router-link to="/home/news">News</router-link>
    
  3. Target placements

    <router-view></router-view>
    

5.5 Query parameters of routing

  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.6 Named routing

  1. Function: It can simplify routing jumps.

  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>
      

5.7 Params parameters of routing

  1. Configure routing and 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 note: When the route carries params parameters, if you use the object writing method of to, the path configuration item cannot be used, and the name configuration must be used!

  3. Receive parameters:

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

5.8 Routing props configuration

Function: Make routing components more convenient 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,
		  a: 1,
		  b: 'hello'
		}
	}
}

Convenient for easier writing in the component to be jumped to

Jump to the specific code of the component

<template>
  <ul>
      <h1>Detail</h1>
      <li>消息编号:{
   
   {id}}</li>
      <li>消息标题:{
   
   {title}}</li>
      <li>a:{
   
   {a}}</li>
      <li>b:{
   
   {b}}</li>
  </ul>
</template>

<script>
export default {
      
      
    name: 'Detail',
    props: ['id', 'title', 'a', 'b'],
    mounted () {
      
      
        console.log(this.$route);
    }
}
</script>

<style>

</style>

5.9 <router-link>replace attribute

  1. Function: Control the mode of operating browser history when routing jumps
  2. There are two ways to write browser history: push and replace, push is append History record, replace is to replace the current record. The default is when routing jumpspush
  3. How to turn onreplacemode:<router-link replace .......>News</router-link>

5.10 Programmatic routing navigation

  1. Function: Implement routing jump without the help of<router-link> , making routing jump more flexible

  2. Specific coding:

    //$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() //可前进也可后退
    

5.11 Cache routing component

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

  2. Specific coding:

    This include refers to组件名

Cache a routing component

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

Caching multiple routing components

<keep-alive :include="['News', 'Message']"> 
    <router-view></router-view>
</keep-alive>

5.12 Two new lifecycle hooks

Function: Two hooks unique to routing components, used to capture the activation status of routing components.
Specific name:

  • activatedFired when the routing component is activated.
  • deactivatedTriggered when the routing component is deactivated.

These two life cycle hooks need to be used in conjunction with the previous cache routing component (it will not work without the cache routing component)

5.13 Route guard

  1. Function: Control permissions on routing

  2. Category: Global Guard, Exclusive Guard, In-Component Guard

  3. Global guards:

    //全局前置守卫:初始化时执行、每次路由切换前执行
    router.beforeEach((to,from,next)=>{
          
          
    	console.log('beforeEach',to,from)
    	if(to.meta.isAuth){
          
           //判断当前路由是否需要进行权限控制
    		if(localStorage.getItem('school') === 'zhejiang'){
          
           //权限控制的具体规则
    			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'
    	}
    })
    

    Complete code

// 这个文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About.vue'
import Home from '../pages/Home.vue'
import Message from '../pages/Message.vue'
import News from '../pages/News.vue'
import Detail from '../pages/Detail.vue'
// 创建并暴露一个路由器
const router = new VueRouter({
    
    
    routes: [
        {
    
    
            path: '/home',
            component: Home,
            meta:{
    
    title:'主页'},
            children: [
                {
    
    
                    path: 'news',
                    component: News,
                    meta:{
    
    isAuth:true,title:'新闻'}
                },
                {
    
    
                    path: 'message',
                    name: 'mess',
                    component: Message,
                    meta:{
    
    isAuth:true,title:'消息'},
                    children: [
                        {
    
    
                            path: 'detail/:id/:title',
                            name: 'xiangqing',
                            component: Detail,
                            meta:{
    
    isAuth:true,title:'详情'},
                            props($route) {
    
    
                                return {
    
    
                                    id: $route.query.id,
                                    title:$route.query.title,
									a: 1,
									b: 'hello'
                                }
                            }
                        }
                    ]
                }
            ]
        },
        {
    
    
            path: '/about',
            component: About,
            meta:{
    
     title: '关于' }
        }
    ]
})

// 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
    
    
    console.log('前置路由守卫', to, from);
    if(to.meta.isAuth) {
    
    
        if(localStorage.getItem('school') === 'zhejiang') {
    
    
            // 放行
            next()
        } else {
    
    
            alert('学校名不对,无权查看')
        }
    } else {
    
    
        next()
    }
})

// 全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
    
    
    console.log('后置路由守卫', to, from)
    document.title = to.meta.title || '我的系统'
})

export default router
  1. Exclusive guard:

Just write the guard in the routes sub-route

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()
	}
}

Insert image description here

  1. Guard within the component:

Write guards within specific components

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

Insert image description here

5.14 Two working modes of 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 unsightly.
    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. The 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 online, support from back-end personnel is required to solve the problem of 404 on the server side when refreshing the page.

Insert image description here

6 Vue UI complex

Guess you like

Origin blog.csdn.net/m0_57809042/article/details/129689157