This is the fifth day of my participation in the More text Challenge. For details, see more text Challenge

Vue Router is part of the Vue ecosystem and is an MIT licensed open source project. Vue-router4.x is available in Vue3. X, with some changes and additions to Vue-Router3.x. Let’s see how to use vue-Router4.x

The installation

Replace new Router() with createRouter

  • Previous version of writing
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'

Vue.use(Router)

const router = new Router({
  routes
})
export default router

// main.js
import Vue from 'vue'
import router from './router'
// ...

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
Copy the code
  • vue-router 4.xVersion of the writing
// router/index.js
import { createRouter } from 'vue-router'
import routes from './routes'

const router = createRouter({
  routes
})

// main.js
import { createApp } from 'vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app'All navigation is asynchronous. If you use Transition, you need to wait for the router to be ready before installing the application.// Router.onReady () has been replaced with router.isready ()
// Return Promise without any arguments
router.isReady().then(() = > app.mount('#app'))
Copy the code

Mode change

  • mode: ‘history‘option has been replaced with a more flexible namehistory
vue-router 3.x vue-router 4.x
history createWebHistory()
hash createWebHashHistory()
abstract createMemoryHistory()
  • baseThe option is removed and changed tocreateWebHistoryAnd so on method first argument passed
/ / the original writing
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'

Vue.use(Router)

const router = new Router({
  mode: 'history'.base: process.env.BASE_URL,
  routes
})
export default router

/ / a new way
import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'

const router = createRouter({
  // history: createWebHistory(),
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router
Copy the code
  • inSSR, you need to manually pass the appropriatehistory
let history = isServer ? createMemoryHistory() : createWebHistory()
let router = createRouter({ routes, history })
// somewhere in your server-entry.js
router.push(req.url) // request url
router.isReady().then(() = > {
  // resolve the request
})
Copy the code

Composition API

UseRouter, useRoute

 // Return a route whose name is About
    // No error will be reported
    console.log(router.resolve({ name: 'About' }))

    watch(
      () = > route.params,
      async newParams => {
        userData.value = await fetchUser(newParams.id)
      }
    )

    function pushWithQuery(query) {
      router.push({
        name: 'search'.query: {
          ...route.query
        }
      })
    }

    return {
      pushWithQuery,
      userData
    }
  }
}
Copy the code

OnBeforeRouteLeave, onBeforeRouteUpdate

import { ref } from 'vue'
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'

async function fetchUser(id) {}

export default {
  setup() {
    const userData = ref()

    onBeforeRouteLeave((to, from) = > {
      const answer = window.confirm(
        'Do you really want to leave? you have unsaved changes! '
      )
      if(! answer)return false
    })

    onBeforeRouteUpdate(async (to, from) = > {if(to.params.id ! = =from.params.id) {
        userData.value = await fetchUser(to.params.id)
      }
    })

    return {
      userData
    }
  }
}
Copy the code

Dynamic routing

  • router.addRoute(route: RouteRecord): dynamically adds a route
  • router.removeRoute(name: string | symbol): dynamically deletes a route
  • router.hasRoute(name: string | symbol): Checks whether the route exists
  • router.getRoutes(): Obtains the route list

Whenever a route is deleted, all its aliases and descendants are deleted

router.addRoute({ path: '/about'.name: 'about'.component: About })
// The name should be unique. The system deletes the original route before adding a new route
router.addRoute({ path: '/other'.name: 'about'.component: Other })

const removeRoute = router.addRoute(routeRecord)
// Delete the added route
removeRoute()

router.addRoute({ path: '/about'.name: 'about'.component: About })
// If the route name is added, you can directly delete the route with the corresponding name
router.removeRoute('about')

// Set set by
router.addRoute({ name: 'admin'.path: '/admin'.component: Admin })
// The first parameter admin is the name of the parent route
router.addRoute('admin', { path: 'settings'.component: AdminSettings })

const routeRecords = router.getRoutes()
Copy the code

Navigation guard

Typically used to check if a user has access to a page, verify dynamic route parameters, or destroy the listener after the custom logic is run, the next callback is used to confirm the route, declare an error, or redirect the vue-Router 4.x can return a value or Promise from the hook instead

The return value:

False: cancel the current navigation. If the browser URL is changed (manually by the user or via the back button), it will be reset to the URL of the from route a router location: Redirect to a different location by passing, if you are calling path location router.push(), it allows you to pass similar options replace: true or name: ‘home’. From returns nothing, undefined, or true returns anything, the navigation is validated, and the next call throws an exception: Cancel the navigation and call the callback router.onError().

/ / the original writing
router.beforeEach((to, from, next) = > {
  if(! isAuthenticated) { next(false)}else {
    next()
  }
})

/ / a new way
router.beforeEach(() = > isAuthenticated)
Copy the code

Router-view, keep-alive, transition

Transition and keep-alive must go inside the router-view

<router-view v-slot="{ Component }">
  <transition>
    <keep-alive>
      <component :is="Component" />
    </keep-alive>
  </transition>
</router-view>
Copy the code

What’s new and before and after the comparison is about these, what is not welcome to correct, the following will be vue-Router4.x source parsing