Vue3 中应用 vue-router
- 首先装置 vue-router
cnpm i vue-router@next
- 在 router 文件夹下新建 index.js
import { createRouter, createWebHashHistory, createWebHistory } from "vue-router"//1. 定义要应用到的路由组件 (肯定要应用文件的全名,得蕴含文件后缀名)import index from "../components/index.vue"import ywcz from "../components/ywcz.vue"//2. 路由配置const routes = [ //redirect 重定向也是通过 routes 配置来实现,上面就是从 / 重定向到 /index { path: "/", redirect: "/index", }, { path: "/index", component: index }, { path: "/ywcz", component: ywcz },]// 3. 创立路由实例const router = createRouter({ // (1)采纳hash 模式 history: createWebHashHistory(), // (2)采纳 history 模式 // history: createWebHistory(), routes, //应用上方定义的路由配置})// 4. 导出routerexport default router
- 在 main.js 引入 router
import router from "./router" //匹配本人我的项目所对应的门路createApp(App).use(router).mount("#app") //应用配置的路由
- 在 App.vue 应用
<!-- <router-view> 组件是一个 functional 组件,渲染门路匹配到的视图组件 --><div> <router-view></router-view></div>