SoFunction
Updated on 2025-04-12

Vue Router4 and Router3 routing configuration and difference description

Routing installation

  • Vue 2 (using Vue Router 3):
npm install vue-router@3
  • Vue 3 (using Vue Router 4):
npm install vue-router@4

Routing configuration

vue-router 3 version writing

Configure routing

// router/  
import Vue from 'vue'  
import Router from 'vue-router'  
import Home from '../views/'  
import About from '../views/'  
  
(Router)  

const routes = [  
  {  
    path: '/',  
    name: 'Home',  
    component: Home  
  },  
  {  
    path: '/about',  
    name: 'About',  
    component: About  
  }  
]  

export default new Router({  // Difference 1  mode: 'history',  // Difference 2  base: .BASE_URL,  
  routes 
})

Using routing

//   
import Vue from 'vue'  
import App from './'  
import router from './router'  
  
new Vue({  
  router,  
  render: h => h(App)  
}).$mount('#app')  // the difference3  

vue-router 4 version writing

Configure routing

// router/
import { createRouter, createWebHistory } from 'vue-router'  
import Home from '../views/'  
import About from '../views/'  
  
const routes = [  
  {  
    path: '/',  
    name: 'Home',  
    component: Home  
  },  
  {  
    path: '/about',  
    name: 'About',  
    component: About  
  }  
]  
  
const router = createRouter({  // Difference 1  history: createWebHistory(.BASE_URL),  // Difference 2  routes  
})  
  
export default router

Using routing

//   
import { createApp } from 'vue'  
import App from './'  
import router from './router'  
  
const app = createApp(App)  
(router)  // Difference 3('#app')

Difference between Vue Router 4 and Vue Router 3

  • Compatibility with Vue versions: Vue Router 4 is designed specifically for Vue 3, which is compatible with Vue 2.
  • Composition API integration: Vue Router 4 provides better support for the Vue 3 Composition API, allowing you to useuseRouteanduseRouterHooks access routing information in a combined component.
  • TypeScript Support: Vue Router 4 provides better support for TypeScript, and the type definition is more complete and accurate.
  • Router Guard Improvements: Vue Router 4 improves the Router Guard (Navigation Guard) API, providing more flexibility and control.
  • Scrolling Behavior: Vue Router 4 improves the management of scrolling behaviour, allowing for finer granular control.

Specifically reflected in:

  1. Depend oncreateRouter()replacenew Router()
  2. Routing mode iscreateWebHistory()replacemode: 'history'
  3. Zhongyu.use(router)replacenew Vue({ router })

Differences in routing modes

vue-router vue-router
history createWebHistory()
hash createWebHashHistory()
abstract createMemoryHistory()

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.