安装vue-router:
(注意:vue2引用vue-router@3 vue3才引用vue-router@4)
npm install vue-router@4
src文件夹下面创建 router/index.ts(或index.js):
测试代码 (注意,login.vue reg.vue 组件你可自己写测试页面):
import { createRouter,createWebHashHistory } from "vue-router";
// typeScript 语法
const routes:Array<any> = [
{
path: "/",
name: "home",
component: () => import("../App.vue")
},
{
path: "/login",
name: "login",
component: () => import("../components/login.vue")
},
{
path: "/reg",
name: "reg",
component: () => import("../components/reg.vue")
},
]
const router = createRouter({
// createWebHistory():地址栏不带#号,createWebHashHistory:地址栏带#号
history: createWebHashHistory(),
routes
})
export default router
注册到vue中:
注意,入口App.vue页面需要引入router的视图组件:
此时即可切换地址栏 进行页面跳转了。
http://127.0.0.1:5173/#/reg
http://127.0.0.1:5173/#/login
router-link 标签使用案例:
编程式调用router:
router传参: