引入 vue-router
本文使用的是vue-router 4.x版本
官方文档:router.vuejs.org/zh/guide/
安装vue-router
npm install vue-router@next -S
配置路由
在src文件夹下创建 router/index.ts 文件; 在src下创建 views/Home.vue 和 views/My.vue 文件作为演示页面
// router/index.ts 文件
import { createRouter, createWebHashHistory, RouterOptions, Router, RouteRecordRaw } from 'vue-router'
//由于router的API默认使用了类型进行初始化,内部包含类型定义,所以本文内部代码中的所有数据类型是可以省略的
//RouterRecordRaw是路由组件对象
const routes: RouteRecordRaw[] = [
{ path: '/', name: 'Home', component: () => import('@/views/Home.vue') },
{ path: '/my', name: 'My', component: () => import('@/views/My.vue') },
]
// RouterOptions是路由选项类型
const options: RouterOptions = {
history: createWebHashHistory(),
routes,
}
// Router是路由对象类型
const router: Router = createRouter(options)
export default router
// main.ts 文件
import { createApp } from 'vue'
import router from '@/router' // ++ 将上一步骤配置 router导入
import App from './App.vue'
createApp(App)
.use(router) // ++ 挂载路由
.mount('#app')
使用router-view占位
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
</script>
<template>
<!--需要渲染的地方用 <router-view>代替-->
<router-view></router-view>
</template>
<style lang="less">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>