“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
The paper
In many ways, Vue and React are not very different in terms of underlying principles and syntax. The underlying principle is more of the same. React has JSX, Vue has Template. In fact, it can be understood as the same thing, is written differently. Hash routing and History Routing briefly introduced the two routing modes of VUE, but what is the principle behind them? React routing Hope to help readers ~~~
Updating the view without rerequesting the page is one of the core principles of front-end routing!
Hash pattern
-
Hash, while present in the URL, is not included in the HTTP request, is used to direct browser action and is completely useless on the server side, so changing the hash does not reload the page.
-
You can add listener events for hash changes: window.addeventListener (‘hashchange’,callBack).
-
Every time a hash(window.localtion.hash) is changed, a record is added to the browser’s access history. Using the above features of hash, it is possible to implement a front-end route that “updates the view but does not re-request the page”.
We can use Hashchange to handle special operations and execute code that would otherwise be executed. Vue/React applies this principle. Call different functions /JS via different routes to generate different page code.
Here’s an example:
// This is an example of a hash mode url http://www.xxx.com/#/abcd123Copy the code
Function callBack(e) {function callBack(e) {function callBack(e) {function callBack(e) {function callBack(e) { Console. log(e.oldurl) console.log(e.newurl)} window.addeventListener ('hashchange',callBack)Copy the code
The lowest version of hash mode currently supported is IE8, which is why hash mode is said to be more compatible. React and Vue hash routing is as simple as this.
The History mode
The History model, that is, http://www.xxxx.com/abc/dcd
This mode causes the browser to re-request the server route, first fetching the file under the corresponding path of the server. 404 Not Found! Of course, this format requires the server to cooperate by redirecting the route to our packaged index.html file.
The History mode is actually the new BOM object History in ES6. Vue and React are also cleverly designed to make use of new ES6 properties. The History of the BOM object added to ES6 is as follows:
Proto contains the replaceState and pushState methods. ReplaceState and pushState are just replace and push in vue, but the authors of vue encapsulate them.
History stores History records are stored in a queue, which can also be understood as an array. It also has a length attribute. Go (num) is used to call the historical data in the History queue, and find the corresponding index for a jump.
Since IE9 only supports ES6, History mode does not support versions below IE9. So Hash mode is more compatible.
This is the basic principle of Vue and React routing.