How does the front-end routing implement the core function of changing the URL without refreshing the page as a whole?

The core of front-end routing is to change the URL without refreshing the page. The specific implementation method:

1. URL hash

The hash of the URL is the anchor point (#), which essentially changes the href attribute of window.location. You can change the href by directly assigning location.hash, but the page does not refresh.
Note: URLs changed by hash are marked with #
insert image description here

2. The history mode of HTML5

The history interface is new to HTML5, and it has five modes to change the URL without refreshing the page.

(1)history.pushState()

insert image description here

This method is actually to change the historical records, and the URL will directly increase /xxx. Secondly, it has three parameters, and the last one is the URL. This one can go forward/backward, because it's like pushing the stack. (Back, go and other methods can be used to move forward or backward.)

  • If you modify location.href = 'songsisi' in the console, the entire page will be refreshed;
  • If you modify it with location.hash = 'songsisi', the page will not be refreshed.
  • Using history.pushState({}, ' ', '/songsisi') will also not refresh anything.
  • history.pushState(); uses a stack structure, and the url pushed every time is at the top of the stack. If history.back() is used, the url at the top of the stack will be popped out of the stack, and the url address of the browser will be back.

(2)history.replaceState()

insert image description here

This is the same as pushState, but this one does not have forward and backward functions. The browser will not save your records, and will directly overwrite the original url instead of pushing it into the stack, so it cannot return.

(3) history.back() is equivalent to history.go(-1)

Equivalent to back in the browser interface
insert image description here

(4) history.forward() is equivalent to history.go(1)

The forward equivalent of the browser interface
insert image description here

Guess you like

Origin blog.csdn.net/Maybe_ss/article/details/122342898