Summary of vue-router project and summary of vue-router practice

Source: Internet
Author: User

Summary of vue-router project and summary of vue-router practice

Let's talk about the vue project {vue,vue-router,component} One of the three major gods is vue-router. As one of our very important practices of front-end and back-end separation, router helps us complete page jump between SPA applications.

In addition, with a third-party library such as axios, we can implement the interceptor function that works with the background interface.

For a small project, the folder router contains a router. js,

However, when there are many pages, we need to separate two files: one to define our routes and components, and the other to instantiate components, and mount the route to the vue instance.

The basic usage will not be repeated. You can refer to the official website of vue-router. If you have carefully done this, it is certainly no problem to use it.

1. Why does my path not work?

An important point here is the parameter passed in when we construct a VueRouter instance.

Import routes from '@/router' const router = new VueRouter ({routes // (ES6 syntax) is equivalent to routes: routes}) new Vue ({router }). $ mount ('# app ')

If routes is not introduced here, you need to write it as follows.

import vRoutes from '@/router/router'const router = new VueRouter({ routes :vRoutes })new Vue({ router}).$mount('#app') 

2. Implement component lazy loading based on webpack in Routing

For our vue projects, we basically use webpack for packaging. If there is no lazy loading, the packaged files will be abnormally large, resulting in a white screen of the homepage, serious latency, and poor user experience, by using lazy loading, you can divide pages. webpack packs different components into many small js files. When needed, load it asynchronously to optimize the user experience. In other words, some pages may have only one or two 100 users, so why do you need to spend traffic on them.

import App from '@/App.vue'const index = r => require.ensure([], () => r(require('@/pages/index/index')), 'index')export default [{ path: '/', component: App, children: [  {    path: '/index',    name:'index',    component: index  }]}]

If a component contains a nested route, we can package the two routes into a js chunk.

// These two routes are packaged in the same block. When you access any route, the routing component const orderUser = r => require is delayed. ensure ([], () => r (require ('@/pages/order/user'), 'order') const payRecord = r => require. ensure ([], () => r (require ('@/pages/order/payRecord'), 'order ')

3. router Mode

For browsers, our router is divided into two modes.

1. hash mode (default)

According to the basic structure of a uri, the hash mode is processed in a basic URI fragment. If you leave SPA alone, a common application scenario is that when we create a pc mall, we will switch tabs such as product details, comments, and product parameters, you can use the tag with the id, and add a special motion effect, the effect is very good.

This is also the default routing method used by the router. However, this method has one drawback: When we connect to a third-party payment, we pass in a url to the third-party payment as the callback address, but after the payment is complete, some third-party payments use our # As a truncation symbol. Only the url content before the first # symbol is retained, and corresponding callback parameters are added later. As a result, you cannot jump to the corresponding payment page after the payment is complete.

Input url:

Http://xx.xx.com/#/pay/123

Address after callback:

Http://xx.xx.com/pay/123? Data = xxxxx % xxxx

2. history Mode

Another mode is history. It uses h5's history. pushState to redirect URLs. The advantage of using this method to handle redirection is that the url is no different from what we usually see. If it is compared with the hash mode, no # is available #. However, when using the history mode, we also need to perform corresponding processing in the background, because if we directly access an address, such as http://www.xxxx.com/user/id', the backend will return pages if there is no configured time.

4. router-link in the loop this. parameter name = undefined

The <router-link> component is the jump component we need in the view layer. It replaces what the <a> label needs to do and helps us do more.

Whether it is in h5 history mode or hash mode, it performs the same behavior. Therefore, when you want to switch the routing mode or downgrade the hash mode in IE9, there is no need to change it.

In HTML5 history mode, the router-link guard the click event so that the browser does not reload the page.

When you use the base option in HTML5 history mode, all the to attributes do not need to be written (the base path.

However, when we use router-link in the v-for loop, generally, we need to take all the values in the loop, which can be obtained through the defined item. xxx. If we want to obtain a value defined in data, we use this. foo to retrieve it? Or through foo? Or both?

Here, we cannot use this. foo to retrieve this, because this is not a vue instance, but an object Window. Therefore, if this. foo is used to retrieve the data, it is actually undefined.

<Router-link tag = "li": to = "{path: '/user/$ {item. userID} '} "v-for =" (item, index) in userList ": key =" index "> // contains a fixed value <p >{{ this. foo }}</p> <p >{{ foo }}</p> </router-link> data () {return {foo: 'bar ',}}

4. Use vue-router with axios

The concept of the first contact interceptor is that in java, through the interceptor, we can perform more granular operations on the user's logon status. For a SPA application, without the intervention of background routing, we need to implement a set of login status management mechanism at the front end.

The most intuitive one is to use the user's token to determine whether the user is logged on?

router.beforeEach((to, from, next) => { const NOW = new Date().getTime(); if (to.matched.some(r => r.meta.requireAuth)) {  if(NOW > store.state.deadLine){   store.commit('CLEAR_USERTOKEN')  }  if (store.state.message.login === true) {   next();  }  else {   next({    path: '/login',    query: {redirect: to.fullPath}   })  } } else {  next(); }})

In the above Code, we use the global guard in vue-router to do the following things during navigation triggering:

(1) determine whether to log on to the navigation page

(2) Clear persistent logon user tokens when the logon duration is exceeded.

(3) If the logon period is not exceeded, check whether the logon status is correct.

(4) No Logon. Redirect to the logon page

However, this alone is not enough. It is normal for the user to directly run the webpage in the background because the user does not log out normally. This causes the token to exist, but this token is invalid in the background, expired. Therefore, we need axios to work with the status code provided by the background to improve our interceptor.

Import router from '@/router/routes' axios. interceptors. response. use (success => {switch (success. code) {case-100: router. replace ({path: 'login', query: {redirect: router. currentRoute. fullPath}) console. warn ('Note: logon has expired! ') Break;} return success;}, error => {switch (error. code) {case 404: console. warn (' the request address is incorrect or the parameter is incorrect! ') Break;} return Promise. reject (error. response. data )});

The logon expiration status code sent from the backend. Here we use-100 as an example. We can use the axios response Interceptor. When our token expires, we will redirect the page to the logon page.

5. replace push with replace

In the project, some of my colleagues are alwaysthis.$router.push(...), From start to end.

Some pages, for example, you need to know the current city of the user when selecting the address. If not, you need to redirect to the city list page to manually select the address. After the selection is complete, return to the selected address page. If push is used all the time, click back of the selected address to go back to the city list page. Then it causes an endless loop between pages.

If replace is used here, there is no problem. The problem is that we should not make the city list page appear in our browsing history.

Summary

The above is a summary of the practical use of the vue-router project. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.