[Vue learning notes _15] Vue Router front end routing

Supporting executable code example = > GitHub

Development history of front-end routing

Routing: the activity of transmitting information from a source address to a destination address over an interconnected network

Router provides two mechanisms: routing and forwarding

  • Routing: determines the path of a packet from the source address to the destination address
  • Forwarding: forward the data packets at the input end to the appropriate output end through the routing table (the mapping table of Intranet IP and Mac address of each computer)

Render Back-End

The server directly renders the entire HTML page and returns it to the client. In this case, the rendered page does not need to load any js and css separately. It can be directly presented to the browser, which is also conducive to SEO optimization. For example, JSP reads data from the database and renders the data to the page.

Disadvantages:

  • In one case, the modules of the whole page are written and maintained by back-end developers
  • Another situation is that if front-end developers want to develop web pages, they need to write web page code through languages such as PHP and Java
  • Usually, HTML code and data and their corresponding logic are mixed together, and writing and maintenance are very bad

Back end routing

The backend processes the mapping relationship between the URL and the page. The URL is sent to the server. The server matches the URL through regular, and finally gives it to a Controller. The Controller performs various processing, and finally generates HTML or data and returns it to the front end.

Front end rendering (front and rear end separation)

With the emergence of Ajax, there is a development mode of front-end and back-end separation. The back end only provides API s to return data. The front end obtains data through Ajax and executes it in the browser through JavaScript to render the data to the page. For example, JQuery framework.

advantage:

  • The front and back ends have clear responsibilities, the back end focuses on data, and the front end focuses on interaction and visualization
  • When the mobile terminal (IOS/Android) appears, the back end does not need any processing, and the previous set of API s can still be used

Front end routing (single page rich application)

The front end handles the mapping relationship between URL and page. Single page rich application (SPA) adds a layer of front-end routing on the basis of front-end and back-end separation.

The front end saves a set of static resources of html+css+js. When the URL changes, the front end takes out part of js for rendering. The page does not refresh as a whole, so there is no need to request resources from the server. In Vue development, a URL corresponds to a Vue component.

How to change the URL without refreshing the page?

  • Hash of URL (default): that is, anchor (#), which essentially changes the href attribute of window.location. You can change the href by directly assigning a value to location.hash, but the page does not refresh.
  • History of HTML5: the history page is stored in the stack structure, and the top of the stack is the current page
    • history.pushState({},'','home '), jump to the / home page and merge into the stack
    • history.go(num): jump to a page on the stack
    • History. Back() < = > history. Go (- 1): return to the previous page of the stack
    • History. Forward() < = > history. Go (1): jump to the next on the stack
    • history.replaceState({},'','home '), replace the current page with the / home page, and cannot return

Basic use of Vue router

At present, the three popular front-end frameworks have their own routing implementation:

  • ngRouter of Angular
  • ReactRouter of React
  • Vue router of Vue

Vue router is Vue's official routing plug-in, which is suitable for building single page applications. Vue router is based on Routing and components. Routing is used to set the access path and map the path to components. The path change of the page is the switching of components.

Use steps:

  1. Create routing components in the components / directory

  2. Configure the route mapping information in the router/index.js file

    import Vue from 'vue'
    import Router from 'vue-router'
    import Home from '@/components/Home'
    import About from '@/components/About'
    
    //1. Vue.use (plug-in): install the routing plug-in
    Vue.use(Router)
    
    //2. Create a routing instance and export it
    export default new Router({
      //Configure the mapping relationship between paths and components
      routes: [
        {
          path: '/home',
          component: Home
        },
        {
          path: '/about',
          component: About
        }
      ]
    })
    
  3. Mount the created routing instance in the Vue instance of the main.js file

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    
    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })
    
  4. Use routing through < router link > and < router View > in the template of App.vue file. Router link is used for route navigation and will be rendered as a < a > tag. Router view is used for placeholders to determine where components are rendered. They are built-in components of Vue router.

    <template>
      <div id="app">
        <router-link to="/home">home page</router-link>
        <router-link to="/about">about</router-link>
        <router-view></router-view>
      </div>
    </template>
    

Default route

For example, when users enter the website, they want to display the home page component by default. You can redirect the default path to the path of a component in router\index.js.

routes: [
  {
    path: '',
    redirect: '/home'
  }
]

Using the history mode of HTML5

There are two ways to change the URL without refreshing the page. The hash of the URL is used by default. If you want to use the history mode of HTML5, you can configure it in router\index.js as follows:

export default new Router({
  routes: [
    ...
  ],
  mode: 'history'
})

Router link attribute supplement

  • To: Specifies the path to jump
  • Tag: specifies what components are rendered after < router link >, and the default is the < a > tag
  • replace: Specifies that no history record is left, so the return key cannot return to the previous page
  • Active class: when the route corresponding to < router link > matches successfully, a router link active class will be automatically set for the current element. The default name of the class can be modified through active class
<router-link to="/home" tag="button" replace active-class="active">home page</router-link>

Jump route through js code

Sometimes, you may need to execute some code while jumping the page. At this time, you can use js code to jump the route.

<button @click="homeClick">home page</button>
homeClick() {
  //Jump route using js code
  this.$router.push('/home')
}

Vue router dynamic routing

In some cases, the path of a page may be uncertain. For example, when we enter the user interface, we want to follow the userId in addition to the previous / user. This matching relationship between path and component is called dynamic routing. It is also a way of routing data.

//router\index.js
routes: [
  {
    path: '/user/:userId',
    component: User
  }
]
<!--components\User.vue-->
<template>
  <div>
    <h2>I am the user interface</h2>
    <p>I'm a user{{$route.params.userId}}Information about</p>
  </div>
</template>
<!--App.vue-->
<template>
  <div id="app">
    <router-link :to="/user/+userId">user</router-link>
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      userId: 'Perry'
    }
  }
}
</script>

Note: $router is the vueroter instance from new. If you want to jump to different URL s through code, you can use the $router.push() method$ Route is the currently active route object configured through routes, from which you can obtain params, query and other properties.

Lazy loading of routes

Analysis of the project package file in dist/static/js / Directory:

  • app.xxx.js: all business codes for application development
  • vendor.xxx.js: third party code, such as Vue / Vue router / Axios
  • manifest.xxx.js: provide the underlying support for the packaged code, such as import and export

When packaging and building a very complex application, app.xxx.js will become very large. If the entire page is requested from the server at one time, it may take some time, and even the client will appear a short blank. If we can package the components corresponding to different routes into different JS files and load the corresponding components only when the route is accessed, it will be more efficient. This is route lazy loading, that is, it will be loaded when it is used.

//router/index.js
const Home = () => import('@/components/Home')
const About = () => import('@/components/About')
export default new Router({
  routes: [
    {
      path: '/home',
      component: Home
    },
    {
      path: '/about',
      component: About
    }
})

In this way, two more small js files will be generated in dist/static/js / directory after the project is packaged. A lazy load corresponds to a js file.

Nested Route

Sometimes we want to access different content through the / home/news and / home/message subpaths under the / home main path. This can be achieved through the children configuration item.

//router/index.js
const HomeNews = () => import('@/components/HomeNews')
const HomeMessage = () => import('@/components/HomeMessage')
routes: [
  {
    path: '/home',
    component: Home,
    children: [
      //Configure default path by redirection
      {
        path: '',
        redirect: 'news'
      },
      {
        path: 'news',
        component: HomeNews
      },
      {
        path: 'message',
        component: HomeMessage
      }
    ]
  }
]
<!--components/Home.vue-->
<template>
  <div>
    <h2>homepage</h2>
    <router-link to="/home/news">Journalism</router-link>
    <router-link to="/home/message">news</router-link>
    <router-view></router-view>
  </div>
</template>

Vue router parameter passing

There are two main methods for routing parameters: params and query

params

That is, dynamic routing

  • Configure routing format: / router/:id
  • Parameter transfer method: splice the corresponding parameters behind the path
  • The path formed after passing: / route / ABC. Parameters can be obtained through $route.params.id

query

  • Configure routing format: / router, that is, normal configuration
  • Parameter passing method: to bind an object, path specifies the path, and query is the parameter
  • Path formed after passing: / route? Id = ABC. Parameters can be obtained through $route.query.id
<!--App.vue-->
<router-link :to="{path:'/profile', query: {name: 'Perry', age: 22}}">Personal Center</router-link>
<!--components/Profile.vue-->
<template>
 <div>
   <h2>Personal Center</h2>
   <p>{{$route.query.name}}</p>
   <p>{{$route.query.age}}</p>
 </div>
</template>

Note: query is suitable for the case where more parameters are passed.

When jumping a route through js code, you can also use params and query to pass parameters:

<button @click="userClick">user</button>
<button @click="profileClick">archives</button>
//params
userClick() {
  this.$router.push('/user/'+this.userId)
},
//query
profileClick() {
  this.$router.push({
    path:'/profile',
    query: {name: 'Perry', age: 22}
  })
}

Navigation guard

How to change the title of a web page in a SPA application? The page title is displayed through < title >, but SPA only has a fixed HTML. When switching between different pages, the title will not change. However, we can assign a value to document.title through js to modify the content of < title >.

The navigation guard provided by Vue router is mainly used to monitor the entry and exit of routes. Vue router provides hook functions of before each (pre hook) and after each (post hook), which will be triggered before and after the route is about to change.

We can use beforeEach to modify the title:

  1. Define the title content in the routing object

  2. The routing instance calls beforeEach, passes in the NavigationGuard function, and modifies the title in it

    Three parameter analysis of navigation guard:

    • To: the routing object to be entered
    • from: the routing object to leave
    • Next: you need to call this method to execute the next step according to the normal process implemented inside vueroter. Other usage: next(false) interrupts the current navigation, and next('/ xxx') jumps to another specified address.
//router/index.js
const router = new Router({
  routes: [
    {
      path: '/about',
      component: About,
      //Use meta to define the title content corresponding to the routing object
      meta: {title: 'about'}
    }
  ]
})

router.beforeEach((to, from, next) => {
  document.title = to.matched[0].meta.title
  next()
})

Note: the above uses global guards. In addition, there are guards exclusive to routes and guards in components.

keep-alive

< keep alive > is a built-in component of Vue, which can keep the contained components in the state and avoid frequent creation and destruction. Router view is also a component. If it is directly wrapped in keep alive, all components matching the path will be cached.

<!--App.vue-->
<keep-alive>
  <router-view></router-view>
</keep-alive>
//components/Home.vue
export default {
  name: "Home",
  data() {
    return {
      path: '/home/news'
    }
  },
  //Called when the component is activated
  activated() {
    this.$router.push(this.path)
  },
  //Called when you are about to leave the route corresponding to the component
  beforeRouteLeave(to, from, next) {
    this.path = this.$route.path
    next()
  }
}

The above code realizes that when entering the / home route, it will jump to the / home/news route by default. When leaving the route, it will record the current path (/ home/news or / home/message). When entering the / home route again, the last state will be retained instead of directly jumping to the default / home/news route.

  • activated(): called when the component is activated. This function and the deactivated() function will take effect only when the component is kept in a state by < keep alive >.
  • Beforeroutleave(): called when leaving the route corresponding to the component. Navigation guard within the component.

Properties of < keep alive >:

  • include: only matching components will be cached, strings or regular expressions.

  • exclude: matching components will not be cached, strings or regular expressions. Note: there must be no spaces before and after commas between components.

    <keep-alive exclude="Profile,User">
    

Tags: Javascript Front-end Vue

Posted on Sun, 28 Nov 2021 00:26:16 -0500 by s.eardley