Detailed explanation of the solution to the problem of vue-router routing parameter refresh and disappearance

怪我咯
Release: 2017-07-04 15:04:39
Original
3232 people have browsed it

This article mainly introduces the solution to the problem of vue-routerrouting parametersrefreshing and disappearing. It has a certain reference value. Interested friends can refer to the

scenario: In the single-page application implemented by vue-router, after the login page callsLogin interface, the server returns the user information and then passes it to the homepage through router.push({name: 'index', params: res.data}) component and display data on the homepage. But after refreshing the page, the data disappeared.

Solution:

1,session&Server rendering

The traditional solution is that the login page and the homepage are two separate pages. After successful login, the server generates a session corresponding to the user information, then renders the homepage data, and passes the sessionid to the browser through the response header and generates the correspondingcookiefile. In this way, the next time the page is requested, the browser will bring the corresponding cookie in the http header, and then the server will determine whether the user is logged in based on the sessionid in the cookie, and then display the user data.
If the project adopts the idea of front-end and back-end separation, and the server only provides interfaces and does not perform server rendering, then this method will not work.

2. $route.query

We can bring the login request parameters when routing:

router.push({name:'index', query:{username: 'xxx', password: 'xxxxxx'}}) ... this.$ajax({ url: 'xxx', method: 'post', data: { username: this.$route.query.username, password: this.$route.query.password } })
Copy after login

The login parameters will be saved in the URL, like this: "http://xxx.xxx.xxx/index?username=xxx&password=xxxxxx", and then the login interface is called in the created hook to return the data.

Even if the password is md5 encrypted, it is definitely unreasonable to put sensitive information such as username and password in the URL.

3. Cookie

Another way is to store the login parameters in the cookie, and then obtain the information stored in the cookie in the created hook. Then call the login interface. It is also unreasonable to store the user name and password in a cookie. The improved version is that the server returns a token after successful login, and the user data is obtained through the token within the validity period.

Cookie data access is more troublesome, because the key-value pairs in the cookie arestringsand are linked by "=", and additional methods for operating cookies need to be written.