Summary of front-end routing knowledge points

Keywords: Javascript Front-end leetcode

1. The core of front-end Routing:

Change the URL without overall refresh:
Implementation methods: 1) hash of URL 2) history of html5

2. hash of URL

location.hash=' '

3. history of HTML5

history.pushState({}, ' ' , 'home' )
history.replaceState({},'','home')
pushState() is like entering and exiting the stack. It is a stack structure that can be reversed later, which is equivalent to retaining the previous records
replace is a direct replacement, which cannot return to the original page

history.go(-1)

history.back(): back one page = = history.go(-1)
history.forward(): Previous page = history.go(1)

Here, you can change to the history mode by setting the mode attribute when creating the vueroter object,

const router = new VueRouter({
  routes,
  // Change the path to history mode, not#
  mode: 'history'
})

4. Routing

Code jump

this.$router.push('/home')

Configure redirect: the implementation can make the path jump to the home page by default, and the router view renders the home page component

{
    path: '',
    redirect: '/home'
  },

5. Dynamic routing

User interface:
/user/userId
1. Define a User component

<template>
  <div>
  <h2>I am the user interface</h2>
  <div>{{UserId}}</div>
  </div>
</template>
<script>
export default {
  name: 'User',
  computed: {
    UserId () {
      // this.$route here indicates which route is currently active, and this.$router refers to the router object defined in index.js
      // this.$route refers to the one currently activated in the routing rules of routes defined in this.$route, so the id here should be consistent with that defined in routes
      return this.$route.params.id
    }
  }
}
</script>
<style scoped>
</style>

2. Configure routing

import User from '../compounts/User.vue'

{
	path: '/user/:id'
	component:User
}

3. Dynamically bind username in App.vue

<template>
  <div>
  <!-- vue-router There are two components registered. One is router-link  One more router-view -->
  <!-- router-link Will be rendered as a Label, and router-view,When a route is switched, it is actually switched router-view Other contents of the mounted components will not be changed -->
    <router-link to="/home">home page</router-link>
  <!-- tag: Render to another component instead of the default a label -->
  <!-- replace :Makes it impossible to return because the default is pushState -->
    <router-link to="/about">about</router-link>
    <!--What's the use here :to To bind data Inside userName,But at this time, there is an expression in the binding-->
    <router-link :to="'/user/'+userName">user</router-link>
    <button @click='btnClick'>change</button>
    <!-- Used to represent the content of the route -->
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      userName: 'guodong'
    }
  },
  components: {

  },
  methods: {
    btnClick () {
      // Change the route through code
      this.$router.push('/about')
    }
  }

}
</script>

<style>

</style>

6. Lazy loading of routes

When packaging the project, the js code will be packaged into different packages
App - > all codes
Manifest - > is the support for the dependencies between the components
Inventor - > refers to the third-party framework code, such as vue, axios, etc

When packaging and building applications, js packages will become very large. At this time, we will divide the components corresponding to different routes into different code blocks, and load the corresponding components only when the routes are accessed, which is more efficient

const routes =[
	{
		path:'/home',
		component:()=>import('../components/Home')
	}

]

Route loading method:
const Home=()=>import ('.../components/home')

7. Nested routing

1. Create corresponding subcomponents and configure the route to correspond to an array through the children attribute

{
    path: '/home',
    component: Home,
    children: [
      // The default path is set here
      {
        path: '',
        redirect: 'news'
      },
      {
        // The path here does not need to write a complete path
        path: 'news',
        component: HomeNews
      },
      {
        path: 'message',
        component: HomeMessage
      }
    ]
  },

2. It is used internally in the home organization

<router-view></router-view>

8. Method of transferring parameters

1. Types of params:
Configure routing format: / router/:id
Transfer method: follow the corresponding value after the path
Path after transfer: / router/123 /router/abc
Get it through this.$route.params.id

2.query type:
URL: protocol: host: port number / path? query
Configure routing format: / router, that is, normal configuration
Transfer method: the object uses the key of query as the transfer method

 <router-link :to="{path:'/profile',query:{name:'guodong',age:22,sex:'man'}}">archives</router-link>

Path formed after transfer: / router?id=123

Value:

{{$route.query.name}}

3. Through buttons and other forms

<button @click="btnClick1">Jump to user interface</button>
<button @click='btnClick2'>Jump to file interface</button>

 btnClick1 () {
      this.$router.push('/user/' + this.userName)
    },
    btnClick2 () {
      this.$router.push({
        path: './profile',
        query: {
          name: 'guodong',
          age: 18
        }
      })
    }

Summary: when routing parameters, select the query method when there are many parameters,
Dynamic routing is used when there are few parameters

9.this. r o u t e r and t h i s . router and this Difference between router and this.route

Actually this r o u t e r Just yes n e w of V u e r o u t e r yes as , in noodles have various species square method , than as p u s h ( ) t h i s . router is the Vuerouter object of new, which has various methods, such as push () this router is the Vuerouter object of new. There are various methods in it. For example, push () this.route is the currently activated routing object, which mainly has param and query attributes

10. Navigation guard:

Lifecycle function:
1.created () {}: this function will be called once the component is created
2.mounted () {}: once the template related things are mounted on the dom tree
3.updated () {}: the page is refreshed once

Called when the route changes

//Front guard
router.beforeEach((to, from, next) => {
  // to and from are route objects, which are through the meta in the matched attribute
  document.title = to.matched[0].meta.title
  console.log(to)
  next()
})

//The post hook runs after the route jump, so there is no need for subsequent operations, so there is no need for the next function,
router.afterEach((to, from) => {
})

Before each and after each here are global guards, that is, these two functions will be called when the route changes

There are also route exclusive guards:

beforeEnter(()=>{

})

And component exclusive guards

11.keep-alive

Keep alive is a built-in component,
His purpose is that when we jump the route, the previous page will not be destroyed, that is, it will not be re created, and then jump back to use the previous page

<keep-alive>
	<router-view/> 
</keep-alive>

Keep alive has two important attributes, include and exclude

<keep-alive include="User,Profile"></keep-alive>

The name attribute of each component is used in include (although the name attribute in the component is rarely used, this is used)

Note: do not habitually add a space after the comma in include

Posted by ririe44 on Fri, 19 Nov 2021 06:16:50 -0800