Vue routing

  1. A route is a group of key-values. Multiple routes need to be managed by routers.
  2. Front-end routing: Key is a path. The value isComponent componentforDisplay page content. When the browser’s path changes, the corresponding component is displayed
  3. Back-end route: Key is a path. The value isFunction is the functionforHandles requests submitted by clients. When the server receives a request, it finds a matching function based on the request path to process the request and return the response data
  4. Vue-router is a plug-in library for VUE that implements SPA applications

1. Basic use

  1. To install vue-router, run the NPM I vue-router command

  2. Use:

    / / SRC/router/idnex. Js
    
    
    // 1. Import Vue
    import Vue from 'vue'
    / / 2. Introducing VueRouter
    import VueRouter from 'vue-router'
    //3. Application plug-in
    Vue.use(VueRouter)
    //4. Import components that need to be displayed in corresponding paths
    import About from '.. /components/About'
    import Home from '.. /components/Home'
    //5. Define routing rules
    const routes =[{
             name:'about'.// Route name
    		path:'/about'.// Jump path
    		component:About // The component of the path}, {name:'home'.path:'/home'.component:Home
    	}]
    //6. Create a Router instance object to manage groups of routing rules and share the instance
    export default new VueRouter({ 
    	routes,
    })
    
    
    / / the main js
    // Import the router
    import router from './router'
    // Mount routes on Vue instances
    new Vue({
        router, // Mount the route
        render: (h) = > h(App),
    }).$mount('#app');
    Copy the code
  3. Specifies where components are displayed

    <router-view></router-view>
    Copy the code

2. Multi-level routing (nested routine)

  1. To configure the routing rule, use the children configuration item:

    routes:[ // Level 1 routing
    	{
    		path:'/about'.component:About,
    	},
    	{
    		path:'/home'.component:Home,
    		children: [// Configure the child route through children
    			{
    				path:'news'.// Do not write: /news here
    				component:News
    			},
    			{
    				path:'message'.// Do not write: /message here
    				component:Message
    			}
    		]
    	}
    ]
    Copy the code
  2. Jump (to write the full path) :

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

3. Route navigation

3.1 Declarative navigation – Basic use
  1. Vue-router provides a global component, router-link
  2. Router-link essentially ends up rendering as a link to the equivalent of providing the href attribute (to without #) with the path character to jump to
  3. Router-link provides declarative navigation highlighting (with class name IS-Active)
<template> <div> <div class="footer_wrap"> <router-link to="/about">about component </router-link> <router-link To ="/home"> Home component </router-link> </div> <div class="top"> </router-view> </div> </div> </template> <script> export default {}; </script> <style scoped> /* omitted other styles */.footer_wrap. Router link-active{color: white; background: black; } </style>Copy the code

Conclusion: Link navigation, with router-link and to, realizes click-to-switch routing

3.2 Routing programmatic navigation

  1. $route.push() $route.push() $route.push()

  2. Specific code:

    <template>
      <div>
          <span @click="btn1">Found that music</span>  
          <span @click="btn2">My music</span>
        <div class="top">
          <router-view></router-view>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      methods: {
        btn1(){
          // Mode 1: Path Hop If there are multiple routing layers, specify the routing paths of each layer
          this.$router.push('/home')},btn2(){
          // Method 2: name Indicates the direct redirect
          this.$router.push('about')}}};</script>
    
    
    
    // Several other apis in the $router
    this.$router.forward() // Forward requests (returns) the previous record route
    this.$router.back() / / back
    this.$router.go() N /-n indicates that n pages can be moved forward or backward
    //this.$router.go(-1): request (return) the last recorded route
    //this.$router.go(1): request the next recorded route
    Copy the code

A few notes:

1. After switching, route components that are “hidden” are destroyed by default and mounted when needed.

2. Each component has its own $route attribute, which stores its own routing information.

3. There is only one router in the entire application, which can be obtained from the $Router attribute of each component (each component has the same $Router attribute).

4 Route forward parameter transfer

4.1. Query parameters of the route

  1. Pass arguments (plus a ‘? x=xxx&y=yyy’)

    <! -- Declarative navigation jump parameter :--> <! <router-link to="/home/message/detail? Id =666&title= hello "> </router-link> <! -- jumps and takes the query argument, <router-link :to="{path:'/home/message/detail', // write to the component query:{// write to the configuration item id:666, </router-link> <! <script> export default {methods: {btn1(){// $router. Push ({path:'/about', query:{id:666, title:' hello '}})}, $router. Push ({name:'about', query:{id:666, title:' hello '}})}}; </script>Copy the code
  2. Receive parameters :(in jump component)

    $route.query.id
    $route.query.title
    Copy the code
    <li>{{$route.query.id}}</li>
    <li>{{$route.query.title}}</li>
    Copy the code

5. Params parameter of the route

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

    {
    	path:'/home'.component:Home,
    	children:[
    		{
    			path:'news'.component:News
    		},
    		{
    			component:Message,
    			children:[
    				{
    					name:'xiangqing'.path:'detail/:id/:title'.// Use placeholder declarations to receive params arguments
    					component:Detail
    				}
    			]
    		}
    	]
    }
    Copy the code
  2. Passing parameters

    <! - jump, and they carry a params argument, string to write - > < the router - link: to = "/ home/message/detail / 666 / hello" > jump < / router - the link > <! <router-link :to="{name:'xiangqing', params:{id:666, title:' xiangqing'}}" > Jump </router-link> <! <script> export default {methods: {btn1(){// methods: $router. Push ({name:'about', params:{id:666, title:' hello '}})},}}; </script>Copy the code

    Note: If the route carries the params parameter, the path configuration item cannot be used. The configuration item must be name!

  3. Receiving parameters:

    $route.params.id
    $route.params.title
    Copy the code

6. Configure the props of the route

Using $route in a component can cause it to be highly coupled to its corresponding route, limiting its flexibility by limiting its use to certain urls. Decouple the component from the route using props, which means it’s better not to use the passed value in the component like this :$route.params.id…..

{
	name:'about'.path:'/about'.component:About,

	// All combinations of key-values in this object are passed to the Detail component through props, and the value is dead
	// props:{a:900}

	// If (props = true), pass all params parameters received to the Detail component through props (this method only manages the invalid params query parameter)
	// props:true
	
	// The third way is that the props value is a function. Each set of key-values returned by this function is passed to the Detail component through props
	props($route){ // The received argument is $route ({query})
		return {
			id:$route.query.id,
			title:$route.query.title
		}
	}
}
// Props receives the value passed in the component with props after configuration
// About component:
<script>
export default {
  props: ['id'.'title'] 
}
<script>
Copy the code

Configured after the props in the component directly use props: [‘ id ‘, ‘title’] received value — — — – > {{id}}, {{title}}

7. Cache routing components

  1. Effect: Keeps undisplayed routing components mounted and not destroyed.

  2. Specific code:

    <! --> <keep-alive include="News"> <router-view></router-view> </keep-alive> <! -- Caches multiple routing components --> <! -- <keep-alive :include="['News','Message']"> -->Copy the code

  3. wrap the display area of the routing component to be mounted.

    include contains the component name, indicating which component to be mounted. If no include is included, all the routing components in the display area are mounted and will not be destroyed during route component switching

8. Two new lifecycle hooks

  1. Purpose: Two hooks unique to a routing component that capture the active status of a routing component.
  2. Specific name:
    1. activatedTriggered when the routing component is activated. (such as switching from another routing component to the current routing component)
    2. deactivatedTriggered when the routing component is inactivated. (for example, cut from the current routing component)

10. Two working modes of the router (mode configuration item)

  1. What is a hash value for a URL? The hash value is # and everything after it.
  2. The hash value is not included in the HTTP request, that is, the hash value is not brought to the server.
  3. Hash mode:
    1. It is not beautiful to always carry # in the address.
    2. If the address is shared through a third-party mobile app in the future, the address will be marked as illegal if the APP has strict verification.
    3. Good compatibility.
  4. The history mode:
    1. The address is clean and beautiful.
    2. Compatibility is slightly worse than hash mode.
    3. When the application is deployed online, the support of back-end personnel is required to solve the problem of refreshing server 404 on the page. The plug-in connect-history-apI-Fallback on the NPM website solves this problem