VueRouter Basics Tutorial series 🎉


What is routing?

Routing, “routing,” is a verb, used mainly in the engineering field, and is defined as:

The act of transmitting information from a source address to a destination address over an interconnected network. – wiki/routing

The application of routing in the software field originated from the server. The client browser sends HTTP requests to the server, and the server performs the corresponding mapping function according to the request address. If the request is for a static resource, the file is read and written. If the request is for a dynamic resource (dynamic data), then a read/write operation to the database is performed.

The early MPA application was a good example of mixing this approach, by loading a template of static resources, combining dynamic data from a database, rendering using a renderer, and returning the rendered page content (HTML strings).

Benefits: good security, good SEO, crawler initiated a request, you can get the complete page content. Disadvantages: Increased pressure on the server, poor user experience (form submission requires opening a new window, page jump needs to trigger the refresh of the entire window).

What is front-end routing?

Front-end routing controls browser page navigation at the front-end layer and updates the page content without refreshing based on address changes. Web applications that are usually implemented based on front-end routing are called SPA applications.

Benefits: Good user experience, less pressure on the server (page content and style are completely generated on the front end, and the back end only needs to provide services with dynamic data). Cons: NOT SEO friendly (this is due to the nature of SPA (page content is created by JS) and search engine not being powerful enough).

Key technical points on which SPA depends:

  • Use Ajax for flexible HTTP requests.
  • throughhashOr is itHTML5 historyMode to achieve no refresh no jump address navigation.

Front-end routing mode

  • Hash mode: Good compatibility, but ugly URLS.
  • History mode: Not compatible, but the URL address format is exactly the same as the common page address.

What are the front-end routing frameworks?

  • Vue -> VueRouter
  • React – ReactRouter
  • Angular -> NgRouter
  • JavaScript -> page.js | director.js

HTML5 history and Hash mode

Browsers support two routing modes:

  • historymodel
  • hashmodel

Hash pattern

In hash mode, the current URL is appended with a string identifier beginning with #, such as #hash=1. The feature is that the page does not refresh, which in combination with hashChange events makes it easy to implement a simple front-end routing function.

<body>
    <a href="#hash=1">hash=1</a>
    <script>
        window.addEventListener('hashchange'.(e) = > {
            console.log(e);//HashChangeEvent
        })
    </script>
</body>
Copy the code

The history mode

History mode is the default routing mode of the browser. The distinctive feature is that when the page’s path changes, the page is refreshed and a GET request is sent to the back end.

With the rapid development of HTML5, modern browsers have enhanced the History mode. Extend pushState(state, NULL, path) and replaceState(state, null, path) methods. You can make the History mode implement the same no-refresh route navigation as the Hash mode. Popstate events are supported to listen for changes in browser browsing history. For example, using history.go(), history.forward(), history.back(), or clicking the forward or back buttons of the browser will trigger the popState event.

The only thing to note is that the pushState() and replaceState() methods do not trigger popState events. If you need to listen for state changes like hash and hashChange, A better approach would be to override the history API’s relevant methods and use custom events to trigger them.


<body>
    <a href="javascript:toSub()">toSub</a>
    <script>
        function toSub() {
            history._pushState({ name: 'sub.html' }, null.'sub.html');
        }

        history._pushState = function () {
            const event = new Event('pushState');
            event.arguments = arguments;
            history.pushState.apply(this.arguments);
            Object.freeze(event);
            window.dispatchEvent(event);
        }

        window.addEventListener('pushState'.(e) = > {
            console.log(e.arguments);
        })
    </script>
</body>
Copy the code

Although the front end in History mode can use pushState or replaceState methods to implement no-refresh route navigation, when the user manually refreshes the current page or re-opens the url of the no-refresh page, a 404 error is generated for a simple reason. A route navigation implemented purely on the front end has no matching route configuration on the back end, so it returns 404.

The solution is simply to add a “fallback” to the backend. For urls that do not match any resources, always provide the application’s index.html page, so that the routing function is passed back to the front end. .

The history and the hash

  • Better hash compatibility, less history requires HTML5 support.
  • Hash path format is not beautiful, SEO support problems, history mode format and traditional page address format is exactly the same, more SEO friendly.
  • The same hash value in hash mode does not trigger a Hashchange and is not added to the history stack, so to solve this problem, we usually provide a timestamp or a random string. The History mode does not have this problem.
  • In the Hash mode, you do not need to configure back – end routing, but in the History mode, you do.

Routes in Vue

In the vue.js foundation, we have seen that a Vue application is composed of many components, which is a complete embodiment of the nested component tree. A route in a Vue is a mapping between a Vue component and a routing address, allowing VueRouter to render the corresponding component according to the change in the navigation address.

For intuitive understanding, you can map the Vue component to the browser address.

VueRouter introduction

The Vue Router is the official routing library of Vue.js, which is deeply integrated with the Vue.js core.

Typically, you can use route configuration to pass props data to the mapped component instance.

More powerful features of Vue Router, including:

  • Nesting route configuration
  • Modular routing configuration based on component mapping.
  • Dynamic route matching
  • Route parameters, wildcard characters, and query.
  • Comprehensive navigation control (declarative, imperative)
  • Automatically activate links to CSS classes
  • Customizable scrolling behavior.
  • HTML5 History mode or hash mode.
  • withtransitionUsed in combination to provide a transitional effect.
  • withkeep-aliveIn combination, provide caching of routing components.

VueRouter installation

Omit the basic CDN introduction and installation of the NPM package.

Vue CLI

If you have a project that is using the Vue CLI (opens new Window), you can add the Vue Router as a project plug-in.

vue add router
Copy the code

Note that this overwrites the app.vue file.

Development build

Always have access to the latest code.

git clone https://github.com/vuejs/vue-router.git node_modules/vue-router
npm install
npm run build
Copy the code

Git clone the latest code from the vue-route. git repository to the vue-router folder in our local project’s node_modules directory. Then install the dependencies and compile VueRouter.

VueRouter will compile the code using Rollup and output it to the dist directory. The way the different versions of the code are introduced is clear from package.json.

{
  "main": "dist/vue-router.common.js"."module": "dist/vue-router.esm.js"."unpkg": "dist/vue-router.js"."jsdelivr": "dist/vue-router.js",}Copy the code