Front end interview - Vue Router

Posted by Adrianphp on Sat, 09 Oct 2021 10:24:11 +0200

VueRouter create

// 1. Define components
const RouterA = { template: `<div>This is Router A</div>` }
const RouterB = { template: `<div>This is Router B</div>` }

// 2. Create a Router instance
const router = new VueRouter({
  routes: [
  {
      path: '/a',
      component: RouterA,
  },
  {
      path: '/b',
      component: RouterB,
  },
]
})

// 3. Mount to Vue
const app = new Vue({
    routes
}).$mount('#app')

Dynamic route matching

Map all routes to which a pattern matches to the same component. Dynamic routing parameters can be used in the routing path of Vue router

<!-- 1. In defining a route -->
<script>
import User from './components/User'

const router = new VueRouter({
    routes: [
        {
            path: '/user/:username',
            component: User,
        }
    ]
})
</script>

<!-- 2. If the original route matches, jump directly to User assembly -->
<template>
	<router-link to="/user/a">User A</router-link>
	<router-link to="/user/bbb">User B</router-link>
	<!-- The page is empty, users and user Mismatch -->
	<router-link to="/users/c">User C</router-link>
</template>

Programming navigation

name and params; path is matched with query.

router.push({ name: 'user', params: { userId: '1' }})
router.push({ path: 'register', query: { plan: 'private' }})
  • router.push(location, onComplete?, onAbort?)

  • router.replace(location, onComplete?, onAbort?)

  • router.go(n)

The default hash mode of Vue router uses the hash of the URL to simulate a complete URL, so the page will not reload when the URL changes.

The difference between hash mode and history mode in Vue router

Formally: the hash mode url always carries a # number. This mode is used by default during development. If users consider the url specification, they need to use the history mode, because the history mode has no # number and is a normal url, which is suitable for promotion;
Function: for example, if we have a sharing page when developing an app, the shared page is made of vue or react. We share this page with third-party apps. In some apps, the url is not allowed to have a # number, so to remove the # number, we need to use the history mode, but there is another problem in using the history mode, When you access the secondary page, a 404 error will appear when you refresh. Then you need to cooperate with the back-end person to configure the url redirection of apache or nginx and redirect it to your home page route

The difference between hash mode and history mode

  • hash mode is ugly and history mode is elegant
  • The new URL set by pushState can be any URL with the same origin as the current URL; The hash can only modify # the following parts, so you can only set the URL of the same document as the current one
  • As like as two peas, the new URL set by pushState can be exactly the same as the current URL, which adds the records to the stack. The new value of hash setting must be different from the original value to trigger the record to be added to the stack
  • pushState can add any type of data to the record through stateObject; hash can only add short strings
  • pushState can additionally set the title property for subsequent use
  • hash is compatible with IE8 and above, and history is compatible with IE10 and above
  • The history mode requires the back-end cooperation to point all accesses to index.html, otherwise the user will refresh the page and cause 404 error

Because the change of hash value will not cause the browser to send a request to the server, and the hash change will trigger the hashchange event, and the browser can control it in advance and backward, people basically used hash to realize the front-end routing before the history of html5.

Navigation guard

const router = new Router({ ... })

// Global front guard
router.beforeEach((to, from, next) => {})
beforeRouteEnter(to, from, next) {
  // Before rendering the component, the corresponding route is called before confirm.
  // no Yes! Get component instance ` this`
  // Because the component instance has not been created before the guard is executed
},
beforeRouteUpdate(to, from, next) {
  // Called when the current route changes but the component is reused
  // For example, for a path / foo/:id with dynamic parameters, when jumping between / foo/1 and / foo/2,
  // Since the same Foo component will be rendered, component instances will be reused. The hook will be called in this case.
  // Can access component instance ` this`
},
beforeRouteLeave(to, from, next) {
  // Called when the navigation leaves the corresponding route of the component
  // Can access component instance ` this`
}
  • beforeRouteEnter
  • beforeRouteUpdate

Route lazy loading

When packaging and building applications, if the JS package is too, it will affect the page loading. We can divide different components corresponding to different routes into different code blocks, and load the corresponding components only when the route is accessed. (combined with Vue's asynchronous component and Webpack's code splitting function)

// First, the asynchronous component is defined as a factory function that returns a Promise
const Foo = () => {
    Promise.resolve({
        // Component definition object
    })
}

// In Webpack 2, dynamic import is used to define code blocking points
import ('./Foo.vue')

// Combine both
const Foo = () => import ('./Foo.vue')

Topics: Vue Interview