Solved: What is the relationship between router and route in Vue? How to reference router and route in external js files? This article makes it clear in a simple way.

When you are new to the front end, especially when you are new to Vue, most of you will use the vue-router library. After all, this library is good enough for routing management, but many friends may not understand the relationship between router and route. How to refer to router and route in the js file, let's first solve how to refer to it in the js file, so as to facilitate the operation of reading and writing routes in the js method:

first part:

Solve how to refer to router and route in js, let’s talk about router first, this is relatively simple, we can directly import the router object in the router.js of the project in the js file, and this object is also created in main.js Vue instance The time object is the same as the this.$router we used in the Vue component. Then you can use the router object to perform operations such as push, replace, and go.

import router from "../router/router";

If you use the route in the js file, you need the router to obtain it. The specific plan is as follows: ignore my business part, we can find that it is actually the app object through the router (the app here is the Vue root instance configured with the router , similar to this in the vue component) gets the current route routing information, and then you can happily use route to get the routing information.

          if (router.app.$route.path.startsWith('/en')){
              router.push('/en/login')
          } else {
              router.push('/login')
          }

the second part:

So far, we have solved the problem raised. Next, we will talk about the relationship between router and route in detail. We often refer to these two words as routing. In fact, router should be called router, and route should be called routing . According to the English part of speech, router is an operator . It is used to perform some write operations on the route and can actually modify the routing data, while route is an information carrier. It is used to modify the current route. For some read operations on the information, the router can only write, but not read. If you want to read through the router, then you need to get the route object under the Vue sample app object and perform the read operation in the way I said above, or leave Do not open the route object. Route can only perform read operations, it can read path, name, meta metadata and so on.

----------------The following are the official key points for router------------------

Router instance

Attributes

router.app

  • type: Vue instance

    Configured  router Vue root instance.

router.mode

router.currentRoute

method

  • router.beforeEach(guard)
  • router.beforeResolve(guard) (2.5.0+) : At this point, the asynchronous component has been loaded
  • router.afterEach(hook)

    Add global navigation hooks. See  Navigation Hooks .

  • router.push(location)
  • router.replace(location)
  • router.go(n)
  • router.back()
  • router.forward()

    Dynamically navigate to a new url. See  Programmatic Navigation .

  • router.getMatchedComponents(location?)

    Returns the target location or an array of components matched by the current route (it is the definition/construction class of the array, not an instance). Usually when server-side rendered data is preloaded.

  • router.resolve(location, current?, append?)

    2.1.0+

    Parse the target location (the format is  the same <router-link> as  to the prop), and return an object containing the following properties:

    {
      location: Location;
      route: Route;
      href: string;
    }
    
  • router.addRoutes(routes)

    2.2.0+

    Add more routing rules dynamically. The argument must be an  routes array conforming to the options requirements.

  • router.onReady(callback)

    2.2.0+

    Add a callback function that will be called when the first route jump is completed. This method is usually used to wait for asynchronous navigation hooks to complete, such as when performing server-side rendering.

--------The following is the official statement about route-------

Routing Information Object

route object (routing information object) represents the state information of the currently activated route, including the information obtained by parsing the current URL, and the route records (routing records)  matched by the URL  .

The route object is immutable (immutable), and a new object will be generated after each successful navigation.

The route object appears in several places:

  • this.$route and  watcher callbacks within components  $route (monitoring change handling);

  • router.match(location) The return value

  • Parameters for the navigation hook:

    router.beforeEach((to, from, next) => {
      // to 和 from 都是 路由信息对象
    })
    
  • scrollBehavior Method parameters:

    const router = new VueRouter({
      scrollBehavior (to, from, savedPosition) {
        // to 和 from 都是 路由信息对象
      }
    })

Properties of the routing information object

  • $route.path

    • type: string

      String, corresponding to the path of the current route, always resolves to an absolute path, eg  "/foo/bar".

  • $route.params

    • type: Object

    A key/value object, including dynamic fragments and full match fragments, if there is no routing parameter, it is an empty object.

  • $route.query

    • type: Object

      A key/value object representing URL query parameters. For example, for paths  /foo?user=1, there is  $route.query.user == 1, or an empty object if there are no query parameters.

  • $route.hash

    • type: string

      The hash value (with) of the current route  #, or an empty string if there is no hash value.

  • $route.fullPath

    • type: string

      The URL after parsing is completed, including the full path of query parameters and hash.

  • $route.matched

    • type: Array<RouteRecord>

    An array containing  route records for all nested path fragments for the current route  . A route record is just  routes a copy of the object in the config array (and in  children the array).

    const router = new VueRouter({
      routes: [
        // 下面的对象就是 route record
        { path: '/foo', component: Foo,
          children: [
            // 这也是个 route record
            { path: 'bar', component: Bar }
          ]
        }
      ]
    })
    

    When the URL is  /foo/bar, $route.matched it will be an object (copies) that contains everything from top to bottom.

  • $route.name

    The name of the current route, if any. (see  named routes )

Digression: Some people say that there is another object called routes. Everyone likes to put routes together for discussion and comparison. I personally understand that routes should not be compared. One is because it has a low sense of existence and there is no room for operation. The second The second is that it is not a functional object. It is passed in as a route array when the router is instantiated. It is an array of construction parameters, which contains many routes. When operating route switching, the router will go to this array. To match the corresponding route, it is enough to understand it to this extent. It is rare to operate this thing, so everyone can understand it.

 

The above is my humble opinion. If there are any mistakes, I hope that the judges will not hesitate to correct them. Friends who need more detailed and professional explanations should read the official documents.

Guess you like

Origin blog.csdn.net/Spy003/article/details/129698413