This is the 9th day of my participation in Gwen Challenge

VueRouter summary

The core idea of a single page jump is to change the URL without refreshing the page

The VueRouter is divided into three modes

  • Hash pattern
  • The History mode
  • Abstract mode (the abstract mode is for non-browser environments. For example, Weex client development, there is no internal browser API, so the vue-router itself will verify the environment, forcibly switch to abstract mode, if the default vue-router configuration item does not write the value of mode. Hash mode is enabled by default in the browser environment, and Abstract mode is used in the mobile client.

Hash pattern

The characteristics of

  1. Is the default mode for VueRouter
  2. Browsers are highly compatible, even with earlier versions of Internet Explorer
  3. It is easier to deploy on the server side than History mode because there are no URL redirection issues
  4. Applied to single-page routing (just switch components on one page)
  5. There’s one in the address bar#No.
  6. #A change in the content after the number does not cause a page-to-server request, so the page does not reload.

Application scenarios

The browser sees a scenario where clicking on a text redirects the page to a fixed location without refreshing the page. This is the browser’s A tag anchor. The Hash pattern has been applied to the routing pattern of single page development. Let’s implement a simple display of controlling page components using Hash.

The Hash pattern has been applied to the routing pattern of single page development. Let’s implement a simple display of controlling page components using Hash. The browser native method provides us with a listening event hashchange that can listen for the following changes:

  • Click the A TAB to change the URL;
  • Browser forward and backward behavior;
  • throughwindow.locationMethod change the address bar;

Hashchange :HTML5 adds a Hashchange event to notify developers when a URL hash value (the part after the last # of the URL) changes. This means that this event is emitted every time the URL hash changes.

Case study:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <ul>
            <! -- Click on the current page because it is an anchor point -->
            <li><a href="#/page1">page1</a></li>
            <li><a href="#/page2">page2</a></li>
        </ul>
        <div id="route-view"></div>
    </div>
    <script type="text/javascript">
        // After the HTML document has been fully loaded and parsed
        window.addEventListener("DOMContentLoaded",Load)
        // Trigger hashchange when the address bar changes
        window.addEventListener("hashchange",HashChange)
        var routeView = null;
        function Load(){
            routeView = document.getElementById('route-view');
            // console.log('routeView_1',routeView);
            // console.log("1")
            // Call the hashchange function once the page is loaded
            HashChange();
            
        }
        function HashChange(){
            console.log('location.hash',location.hash);
            switch(location.hash){
                case '#/page1':
                    routeView.innerHTML = 'page1'
                    return
                case '#/page2':
                    routeView.innerHTML = 'page2'
                    return 
                default:
                    routeView.innerHTML = 'page1'
                    console.log('routeView',routeView);
                    return}}</script>
</body>
</html>
Copy the code

Div routeView: tells you what block it is

Page1,page2: container components equivalent to pages

After the page is loaded, the load function is triggered. Since the browser does not perform hashchange after loading, we need to display a default page, so we need to perform hashchange in the load function. Then click on the a tag to jump to the anchor point, so click on the actual page, change the hash value of the URL according to the href of the A tag, automatically trigger the hashchange event, then trigger the hashchange, Then change the div with the route-view id based on the URL hash value. You can change the value and you can do a lot of things but in this case just change the value.

What is the location. The hash

For example, the current URL is https://anblog.top#2333. Press Enter and type in the console

location.hash
//"#2333"
Copy the code

Histroy mode

The characteristics of

  1. Cannot listen for pushState, replaceState, and A tag changes.
  2. You can listen to the browser moving forward and backward.
  3. good-looking, there is no#
  4. It needs to work with the back end, or 404.

Vue-router defaults to hash mode — the hash of a URL is used to simulate a full URL so that the page does not reload when the URL changes.

If hash is ugly, we can use the history mode of the route, which makes full use of the history.pushState API to do URL jumps without reloading the page.

The pushState, replaceState, and a tags cannot be heard. The solution is to iterate through all of the a tags on the page and block the default event of the A tags

Implement a case

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <ul>
            <li><a href="/page1">page1</a></li>
            <li><a href="/page2">page2</a></li>
        </ul>
        <div id="route-view"></div>
    </div>
    <script>
        // Execute load after the page is loaded
        window.addEventListener('DOMContentLoaded',load)
        // A callback that declares PopChange as popState executes PopChange every time popState is triggered
        window.addEventListener('popstate',PopChange)
        var routeView = null
        function load(){
            routeView = document.getElementById('route-view')
            PopChange()
            // Get all the a tag nodes with href attributes
            var aList = document.querySelectorAll('a[href]')
            // Iterate through the a tag node array, organize the default events, add the click event callback function
            // Foreach runs the passed function on each item of the array, with no return value
            aList.forEach(aNode= > aNode.addEventListener('click'.function(e){
                e.preventDefault();// Block the default event for the A tag
                var href = aNode.getAttribute('href')
                // Browser object history history.pushState(state,title,url)
                // Allows developers to change browser URLS without loading new pages. To do this, use the history.pushstate () method.
                //state: a state object associated with the specified url. This object is passed a callback function when the popState event is triggered. If this object is not needed, null is used
                //title: The title of the new page, but all browsers ignore this value and can be null
                //url: the new url must be in the same domain as the current page
                history.pushState(null.null, href)
                PopChange()
            }))
        }
        // Change the display of that div
        function PopChange() {
            // Window's location property
            //window.location.href Returns the href (URL) of the current page
            // window.location.hostname Returns the domain name of the Web host
            // window.location. pathName Returns the path or filename of the current page
            // window.location.protocol Returns the web protocol used (HTTP: or HTTPS:)
            // window.location.assign loads a new document
            console.log('location',location);
            switch(location.pathname) {
                case '/page1':
                    routeView.innerHTML = 'page1'
                    return
                case '/page2':
                    routeView.innerHTML = 'page2'
                    return
                default: 
                    routeView.innerHTML = 'page1'
                    return}}</script>
</body>
</html>
Copy the code

As you can see from the example, the a tag is bound to the callback function, each time the a tag is clicked, the callback function is executed, and the popState callback function PopChange() is also executed. Popstate listens for changes in the address bar other than pushState and replaceState (such as location.hash, or when the browser moves forward or backward), and concatenates the URL with history.pushState. Then use the callback function to modify the div with the page ID route-View. If the back end is not configured, a refresh is Cannot GET XXX. For example, if you click on page1, a refresh is Cannot GET /page1.

Routing using

The introduction of Vue – the Router

case

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <script src="https://cdn.bootcss.com/vue/2.6.11/vue.min.js"></script>
  <script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
  <title>Vue Router</title>
</head>
<body>
  <div id="app">
    <ul>
      <! -- Use the router-link component to navigate.
      <! -- Specifies the link by passing in the 'to' attribute.
      <! -- <router-link> will be rendered as a '<a>' tag by default.
      <router-link to="/page1">Go to Page1</router-link>
      <br/>
      <router-link to="/page2">Go to Page2</router-link>
    </ul>
    <! -- Route exit -->
    <! -- Routing matching components will be rendered here -->
    <router-view></router-view>
  </div>
  <script>
      // Define routing components, which can also be imported from other files
      const Page1 = {
          template: '<div>Page1</div>'
      }
      const Page2 = {
          template: '<div>Page2</div>'
      }
      // Define a route
      // Each route needs to map one component,
      // Component can also be a component constructor created by vue.extend ()
      // Or just a component configuration object
      const routes = [
          { path: '/page1'.component: Page1 },
          { path: '/page2'.component: Page2 }
      ]
      // create instance VueRouter
      const router = new VueRouter({
          routes:routes
      })
      //4. Create and mount root instances
      // Inject routes through the router configuration parameter to enable routing for the entire application
      const app = new Vue({
          router:router
      }).$mount('#app')

  </script>
</body>
</html>
Copy the code

After running it, you can see that the address bar has a #, and VueRouter does default to hash mode

Gets the change of global route hop parameters

<script>.//4. Create and mount root instances
    const app = new Vue({
        router:router,
        watch: {
            $route(to, from) {
                console.log('to',to);
                console.log('from'.from);
            }
        }
    }).$mount('#app')
</script>
Copy the code

To represents the page parameters after the jump, and from represents the page from which you jump. With these two parameters, we can set the first and second level pages for making cutscenes, and also add the page loading progress bar at the top of the page.

Gets the parameters of the band in the route

There are two ways to pass routing parameters, namely by passing query and Params parameters in to and from

By passing arguments: Pass the query argument of $route

Add parameters to the router-link tag

<router-link :to="{path:'/page1', query:{ id:111 }}">Go to Page1</router-link>
Copy the code

In the figure below, to and from are the $route of the corresponding route

Pass the Params parameter with $route

The route – link component

<router-link to="/page2/222">Go to Page2</router-link>
Copy the code

Defining routing Components

const Page2 = {
    // 2. Pass params
    template: '<div>Page2 {{$route.params.id}}</div>'
}
Copy the code

Define the routing

const routes = [
          { path: '/page1'.component: Page1 },
           // 2. Pass params
          { path: '/page2/:id'.component: Page2 }
      ]
Copy the code

You can see the changes

Redirect page

When a user enters a non-existent route and the vue-Router cannot match it, it needs to return to the home page by default. This requires redirection matching, as shown in the following code

const routes = [
  { path: '/page1'.component: Page1 },
  { path: '/page2'.component: Page2 },
  { path: The '*'.redirect: '/page1'}]Copy the code

This will automatically jump to page1 when you enter a route that doesn’t exist.

Reference:

Router.vuejs.org/zh/guide/#j…

Segmentfault.com/a/119000001…

Juejin. Cn/book / 684473…