“This is the 24th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Where should the data in the input be stored?

1 Scenario Description

A page in a Vue project is routed using router.push and carries the parameter: ID

this.$router.push({
  name: "info".params: { id: this.id }, // Suppose this.id = 'ds'
});
Copy the code

The value of the search box in the destination page is obtained from the route parameter

this.form = {
  id: this.$route.params.id
}
Copy the code

Now if we refresh the page, we’ll see that the value in the search box is empty because we didn’t use dynamic path parameters in the routing path.

// This is how we write it
const routes = [
  { path: '/info'.component: Info }
]

// There is no dynamic path argument
const routes = [
  { path: '/info/:id'.component: Info }
]
Copy the code

This will cause this.$route.params.id to reset to empty when the page is refreshed. Now we want the id in the search box to remain unchanged when the page is refreshed

2 Solution

2.1 Using dynamic Path Parameters

const routes = [
  { path: '/info/:id'.component: Info }
]
Copy the code

Now, even if the page is refreshed, the value of this.$route.params.id remains the same as long as the URL has not changed

2.2 use localStorage

The read-only localStorage property allows you to access a Document source (Origin) object Storage; The stored data is saved in the browser session.

LocalStorage is similar to sessionStorage, but the difference lies in that: Data stored in localStorage can be retained for a long time. When the page session ends — that is, when the page is closed, the data stored in sessionStorage is erased.

We can use localStorage to store the ID locally when the route jumps

localStorage.setItem('id'.this.id)
Copy the code

The value of the search box on the target page is not retrieved from this.$route.params, but from local storage

this.form = {
  id: localStorage.getItem('id')}Copy the code

3 Scene Abstraction

The essence of the problem is how to store values so that they don’t get lost when the page is refreshed. Usually we can concatenate values to urls, store them locally, store them using VUex, etc., depending on the business scenario