在项目里安装vue-router
$ npm install vue-router在src目录下创建router.js , 将vue页面放置在pages目录下
此时的项目结构
├─public
│ └─favicon.ico
├─src
│ ├─App.vue
│ ├─assets
│ │ ├─logo.svg
│ │ └─style.css
│ ├─components
│ ├─main.js
│ ├─pages
│ │ ├─Hello.vue
│ │ └─Login.vue
│ └─router.js
├─index.html
├─jsconfig.json
├─package-lock.json
├─package.json
├─README.md
└─vite.config.js 修改router.js内容
import {createRouter, createWebHashHistory} from "vue-router";
import Login from "/src/pages/Login.vue"
import Hello from "/src/pages/Hello.vue"
// 路由表
// path对应路径, 例如http://localhost:5173/#/hello就会进入Hello对应的vue页面
// component即对应的vue组件对象
const routes = [
{path: "/", name:"Login", redirect:"/hello"},
{path: "/login", name:"Login", component:Login},
{path: "/hello", name:"Hello", component:Hello}
]
// 创建路由
const router = createRouter({
history: createWebHashHistory(),
routes: routes
})
// 导出路由
export default router;修改main.js
import { createApp } from 'vue'
import './assets/style.css'
import App from './App.vue'
import router from './router' // 引入路由
createApp(App)
.use(router) // 挂载路由
.mount('#app')修改App.vue
<template>
<!-- <router-view/> 组件会根据路径返回相应的vue对象 -->
<router-view/>
</template>
<script setup>
</script>
<style scoped>
</style>
路由的使用
// 引用路由
import {useRouter} from 'vue-router'
// 创建路由对象
const router = useRouter()
// 跳转/login路径
router.push("/login")
// router.replace("/hello")
//replace也是跳转路径, 但跳转前的路径不会保存在当前页面历史中, 即跳转后返回上一个页面不再是跳转前的页面了