Vue study notes---------Vue core

Vue study notes---------Vue core (3)

routing

  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: key is the path, and value is the component.

1. Basic use

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

  2. Application plugin: Vue.use(VueRouter)

  3. Write router configuration items:

    //Introduce VueRouter
    import VueRouter from 'vue-router'
    //Introduce the route component
    import About from '../components/About'
    import Home from '../components/Home'
    
    //Create router instance objects to manage groups of routing rules
    const router = new VueRouter({
    	routes:[
    		{
    			path:'/about',
    			component:About
    		},
    		{
    			path:'/home',
    			component:Home
    		}
    	]
    })
    
    //expose router
    export default router
    
  4. Implement switching (active-class can configure the highlight style)

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

    <router-view></router-view>
    

2. A few notes

  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 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 component's $router property.

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', //Do not write here: /news
    				component:News
    			},
    			{
    				path:'message',//Do not write here: /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

    <!-- jump and carry query parameter, to string notation -->
    <router-link :to="/home/message/detail?id=666&title=Hello">jump</router-link>
    				
    <!-- jump and carry query parameter, to object notation -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		   id:666,
               title:'Hello'
    		}
    	}"
    >jump</router-link>
    
  2. Receive parameters:

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

5. Named Routes

  1. Function: It can simplify the jump of the route.

  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 simplifying, you need to write the full path -->
      <router-link to="/demo/test/welcome">jump</router-link>
      
      <!--After simplification, jump directly by name -->
      <router-link :to="{name:'hello'}">jump</router-link>
      
      <!--Simplified writing with passing parameters -->
      <router-link 
      	:to="{
      		name:'hello',
      		query:{
      		   id:666,
                  title:'Hello'
      		}
      	}"
      >jump</router-link>
      

6. The params parameter of the route

  1. Configure the route, declare to receive the params parameter

    {
    	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
    				}
    			]
    		}
    	]
    }
    
  2. pass parameters

    <!-- jump and carry params parameter, to string notation -->
    <router-link :to="/home/message/detail/666/Hello">jump</router-link>
    				
    <!-- jump and carry params parameter, to object notation -->
    <router-link 
    	:to="{
    		name:'xiangqing',
    		params:{
    		   id:666,
                title:'Hello'
    		}
    	}"
    >jump</router-link>
    

    Special attention: When the route carries the params parameter, if the object writing of to is used, the path configuration item cannot be used, and the name configuration must be used!

  3. Receive parameters:

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

7. Routing props configuration

​ Function: 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
		}
	}
}

8. replace attribute of <router link>

  1. Role: control the mode of operating browser history when routing jumps
  2. There are two ways to write the browser's history: push and replace, push is to append the history, and replace is to replace the current record. When the route jumps, the default is push
  3. How to start the replace mode: <router link replace........ > News</router-link>

9. Programmatic Routing Navigation

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

  2. Specific code:

    //Two API s for $router
    pushMsg(m){
        this.$router.push({
            name:'xiangqing',
            query:{
                id:m.id,
                title:m.title
            }
        })
    },
    replaceMsg(m){
     	this.$router.replace({
          	name:'xiangqing',
          	query:{
                id:m.id,
                title:m.title
            }
        })
    },
    this.$router.forward() //go ahead
    this.$router.back() //back
    this.$router.go(number) //Can go forward or backward
    

10. Cache routing components

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

  2. Specific code:

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

11. Two new lifecycle hooks

  1. Role: Two hooks unique to the routing component, used to capture the activation state of the routing component.

  2. Specific name:

    1. Fired when the activated routing component is activated.
    2. Triggered when the deactivated routing component is deactivated.
    activated() {
        console.log('i activated')
        this.timer = setInterval(() => {
            console.log('@')
        },1000)
    },
    deactivated() {
        console.log('I sent')
        clearInterval(this.timer)
    },
    

12. Routing guard

  1. Role: Permission control for routing

  2. Categories: global guards, exclusive guards, in-component guards

  3. Global Guard:

    //Global front guard: executed at initialization, executed before each route 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('name') === 'lai'){ //Specific rules for access control
    			next() //release
    		}else{
    			alert('No permission to view')
    			// next({name:'guanyu'})
    		}
    	}else{
    		next() //release
    	}
    })
    
    //Global post guard: executed at initialization, executed 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){ //Determine whether the current route needs permission control
    		if(localStorage.getItem('name') === 'lai'){
    			next()
    		}else{
    			alert('No permission to view')
    			// next({name:'guanyu'})
    		}
    	}else{
    		next()
    	}
    }
    
  5. In-component guards:

    //Entry guard: Called when entering the component through routing rules
    beforeRouteEnter (to, from, next) {
        console.log('I'm an in-component route guard')
        if(to.meta.isAuth){
            if(localStorage.getItem('name') === 'lai'){
                next()
            }else{
                alert('Username is incorrect')
            }
        }else{
            next()
        }
    },
    //Leaving guard: Called when leaving the component through routing rules
    beforeRouteLeave (to, from, next) {
        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 # 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, the support of the back-end personnel is required to solve the problem of refreshing the page server 404.
    4. Install connect-history-api-fallback to solve

Tags: Javascript Vue.js Vue

Posted by zuperxtreme on Fri, 22 Jul 2022 22:18:37 +0530