vue-router在vue2和vue3中的写法是不同的

427 阅读2分钟

new Router 变成 createRouter

Vue Router 不再是一个类,而是一组函数。现在不用再写 new Router(),而是要调用 createRouter:

// 以前是
// import Router from 'vue-router'
import { createRouter } from 'vue-router'
 
const router = createRouter({
  // 
})

新的 history 配置取代 mode

mode: 'history' 配置已经 history 配置所取代。

根据使用的模式,用适当的函数替换它:

"history": createWebHistory()
"hash": createWebHashHistory()
"abstract": createMemoryHistory()

import { createRouter, createWebHistory } from 'vue-router'
// 还有 createWebHashHistory 和 createMemoryHistory
 
createRouter({
  history: createWebHistory(),
  routes: [],
})


Vue2写法

// 引入vueimport Vue from "vue"

// 引入路由import Router from 'vue-router' 

// 使用路由Vue.use(Router)

// 实例化router并配置参数
let router = new Router({  

// 模式-分为hash与history,不写默认hash模式  mode:"hash",  
// 路由具体配置  
routes:[
    {
     // 名称      
       name:"home",         
    // 地址  '/'代表根目录下,如不写就地址为父组件path加上自生path      
       path:"/home",      
       // 组件地址,此为路由懒加载写法
    component: () => import(组件路径),  
    
       // 子组件,子组件跟父组件写法一样,也可再套children                children:[                                          {                                        name:"son",                                       path:"/son",                    component: () => import(组件路径),
          }
        ]
      },
      // 找不到路径的重定向
      {
           path:"*",
           redirect: {
                 path: "/home"
        }
      }
   ]
 })
 export default router

Vue3写法

// 引入路由函数和路由模式函数
 import { createRouter, createWebHashHistory/createWebHistory} from 'vue-router'; 
 // 实例化router并配置参数
 const router=createRouter({
     // 模式为hash:createWebHashHistory(),模式为history:createWebHistory()
     history:createWebHashHistory()/createWebHistory(), 
    routes:[ 
      {
       // 名称
       name:"home",
       // 地址  '/'代表根目录下,如不写就地址为父组件path加上自生path
       path:"/home",
       // 组件地址,此为路由懒加载写法
       component: () => import(组件路径),
       children:[
         // 子组件,子组件跟父组件写法一样,也可再套children
         {
           name:"son",
           path:"/son",
           component: () => import(组件路径),
         }
       ]
      },
      // 找不到路径的重定向
      {
          // 要写成正则表达式的方式,不能写成*了
       path:"/:pathMatch(.*)",
           redirect: {
                 path: "/home"
        }
      }
   ]
 })
 export default router

对比

// 引用、实例化路由对象对比
import Vue from "vue";import Router from "vue-router";Vue.use("Router");new Router()  变成
import { createRouter, createWebHashHistory/createWebHistory} from 'vue-router'; createRouter()
// 路由模式对比
mode:hash/history 变成 history:createWebHashHistory()/createWebHistory()
// 找不到路径的重定向对比
path:"*" 变成 path:"/:pathMatch(.*)*"

基本用法没有改变,只在引入创建路由实例、路由模式、重定向的写法上有所调整