vue3路由的使用——vue2和vue3的基础用法对比第二篇
vue2写法
// 引入vue
import 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(.*)*"
基本用法没有改变,只在引入创建路由实例、路由模式、重定向的写法上有所调整
作者:博客园-DDjans,转载时请注明来源。
(请勿将文章用在任何商业用途,违者将承担相应法律责任)