在vue3中使用路由

222 阅读1分钟

1.安装

npm i vue-router -S

-S:save,包名会被注册在package.json的dependencies里面,在生产环境下这个包的依赖依然存在。

-D:dev,仅在生产模式下使用。

2.创建路由文件

src下创建router文件夹,在里面的index.js写:

// createRouter 路由
// createWebHashHistory 路由的哈希模式
import { createRouter, createWebHashHistory } from "vue-router"

const routes = [
  {
    path: '/',
    component: () => import('../views/Main.vue'),
    children: [
      {
        path: '/',
        name: 'home',
        component: () => import('../views/home/Home.vue')
      }
    ]
  }
]

const router = createRouter({
  history:createWebHashHistory(),
  routes
})

export default router

图片.png

3.引入和注册路由

在main.js文件中

// 引入路由
import router from './router'

// 注册路由
const app = createApp(App)
app.use(router)

图片.png

4.使用路由