preface

We’ve been using SPA in VUE for a long time, and there are some important updates in VUE – Router4.0.

What is vue-Router?

The Vue router is the official router for vue.js and is deeply integrated with the vue.js core, making it a breeze to build single-page applications with Vue. Features include:

  • Nested route mappings
  • Dynamic routing
  • Modular, component-based router configuration
  • Routing parameters, queries, wildcards
  • View transition effects powered by vue.js transition system
  • Fine-grained navigation control
  • Links with automatic active CSS classes
  • HTML5 history mode or hash mode
  • Customizable scrolling behavior
  • Correct encoding of url

Routing installation

npm i vue-router@next
Copy the code

Routing patterns

  • CreateWebHistory Creates the history routing mode

  • CreateWebHashHistory Creates a hash routing pattern

  • CreateMemoryHistory Creates memory-based history records

All three routes take an optional base argument, the base path before each URL, which defaults to ‘/’

Configure the routing

// router/index import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' const Login = ()=> import('.. /views/login/login.vue') const Home = ()=> import('.. /views/home/home.vue') const About = ()=> import('.. /views/about/about') const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'login', component: Login }, { path: '/home', name: 'home', component: Home, }, { path: '/about', name: 'about', component: About }, ] const router = createRouter({ history: createWebHistory(), routes }) export default routerCopy the code
// main

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'

const app = createApp(App).use(router).mount('#app')
Copy the code

The new router is created using createRouter, RouteRecordRaw is the built-in type interface, and routes is changed to mandatory

Routing slot

  • append
  • event
  • tag
  • exact

The four attributes listed above are no longer in use and are now in scope slots:

<router-link to="/" v-slot="{ href, navigate, isActive }">
  <li :class="{ 'active': isActive }">
    <a :href="href" @click="navigate">
      <span>Home</span>
    </a>
  </li>
</router-link>
Copy the code

And you can manually add an append method globally:

app.config.globalProperties.append = (path:any, pathToAppend:any) =>
path + (path.endsWith('/') ? '' : '/') + pathToAppend
Copy the code



Now you must use transition and keep-alive inside the router-view via the V-slot API.

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

The existing router.onReady function, which accepts no arguments and returns a Promise, has been replaced with router.isReady

Because navigation now includes the first one asynchronously, if you use transition, you need to call isReady before mounting the DOM:

router.isReady().then(()=> app.mount('#app'))
Copy the code

Vue routing and Composition API

This works fine when we use the router-link tag, but when we need to programmatically route to the router, we can’t call the router without this. Do we need to write methods in it? (black question)

This is done by calling the corresponding userRouter function. Note that “import” is introduced at the top, and no return is returned in setup. (There is no code here, you manually click to feel the joy of programming 🤣)

RouterView

In one case, we may need to display multiple routing views on the page at the same time, instead of nesting them, then we need to use the router-view name attribute, which defaults to default:

<router-view>< router-view>< router-view name="about"></router-view> <router-view name="login"></router-view> // router/index const router = createRouter({ history: createWebHashHistory(), routes: [ { path: '/', components: {default: Home, // here is the es6 object for login, // the same about,},},],})Copy the code

Components will correspond to the name in the router-View.

ScrollBehavior change

The object x returned by scrollBehavior is renamed left and y is renamed top.

Route redirection and alias

Redirect refers to the use of various methods to redirect network requests to other locations, such as /home to /

// Const routes = [{path: '/home', redirect: '/'}] // const routes = [{path: '/home', redirect: {name: 'homepage'}}] // const routes = [{path: '/search/:searchText', redirect: to => {return: path: '/search/:searchText'] '/search', query: { q: to.params.searchText } } }, }, ]Copy the code

The router will automatically match the alias, just as we set/to /home, which is equivalent to accessing / :

Const routes = [{path: '/', Component: Homepage, alias: '/home'}] // alias is the key of the aliasCopy the code

Dynamic routing

Dynamic routing may be used in some specific scenarios, so this section describes how to use dynamic routing. Router.addroute () and router.removeroute () can be used for dynamic routing.

Router. AddRoute ({name: 'about', path: '/about', Component: Router. removeRoute(' About ') {path: router.addRoute(' About ', {path: router.addroute (' About ', {path: router.addroute (' About ', {path: router.addroute (' About ', {path: router.addroute (' About ', {path: router.addroute (' About ', {path: Router. AddRoute ({name: 'about', path: '/about', Component: about, children: [{ path: 'profile', component: Profile}], })Copy the code

conclusion

In my opinion, router-link and router-view have been modified to slot mode, which is more difficult but more flexible. We can implement a lot of dark magic in router-link and router-view. In this way, the same function can be implemented in many ways. However, in the project or to pay attention to the unified code standardization, I hope to read this article to help you.