安装路由 Router(TypeScript)
Siona
安装路由 Router(TypeScript)
1. 安装路由 Router
npm install vue-router
# or
yarn add vue-router
2. 配置路由
项目的根目录(通常是 src 文件夹)中,创建一个名为 router.ts
的文件,用于配置路由:
代码一:
// src/router/router.ts
import * as VueRouter from 'vue-router'
const routes = [
{path: '/', component: () => import("@/App.vue")},
{name: 'chart', path: '/chart', component: () => import("@/flowChart/FlowChartApp.vue")},
];
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory("/xxx项目名"),
routes // `routes: routes` 的缩写
});
export default router;
/*
在上面的代码中,我们定义了两个路由
*/
代码二:
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
3. 将路由添加到根实例
打开 main.ts 文件,通常位于项目的根目录,然后将创建的路由添加到根 Vue 实例中:
// main.ts
import {createApp} from 'vue'
import App from './App.vue'
/* 引入路由 */
import router from './router/router'
createApp(App)
.use(router)
.mount('#app')
4. 在组件中使用路由
在需要使用路由的组件中,你可以通过 <router-link>
标签来创建链接,通过 <router-view>
标签来显示对应的组件内容。
// App.vue
<template>
<router-view></router-view>
</template>
<script setup lang="ts">
</script>
<style scoped>
/* 全局去掉内外边距 */
:global(body), :global(#app) {
margin: 0;
padding: 0;
}
/* 不生效,还是有边距 */
/*
body, #app {
margin: 0;
padding: 0;
}
*/
</style>
<template>
<div>
<h1>Home Page</h1>
<!-- 到 关于页面 -->
<router-link to="/about">Go to About</router-link>
</div>
</template>
其他应用
1. 部署到 Linux 中,配置 Nginx
// 首先,在 vite.config.ts 中设置 base 选项
// 例如将 base 设置为 ‘/bigscreen ’
// vite.config.ts
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
/**
* Base public path when served in development or production.
* @default '/'
* resource: index.d.ts -> UserConfig -> base?: string;
*/
base: "/bigscreen",
})
疑问❓ 原来 base 值为 /
,如果加路径的话,应该改为 base: "/bigscreen/"
‼️【待验证】
# 由于 Nginx 配置文件设置了 /bigscreen,because Vue 默认从根目录找,所以找不到目录资源
# /etc/nginx/conf.d/6011.conf
server{
location /bigscreen {
alias /data/vhost/bigscreen/;
}
}
2. 获取 url 中参数
// 不使用 Router 路由,获取 url 中参数
const urlParams = new URLSearchParams(window.location.search);
const dataId = urlParams.get('dataId');
console.log("dataId: ", dataId)
// 使用 Router 路由,获取 url 中参数
// 获取 hash 部分
const hash = location.hash
const searchParams = new URLSearchParams(hash.split('?')[1])
const dataId = searchParams.get('dataId')