安装路由 Router(JavaScript)

Siona

安装路由 Router(JavaScript)

1. 安装路由 Router

npm install vue-router
# or 
yarn add vue-router

2. 配置路由

项目的根目录(通常是 src 文件夹)中,创建一个名为 router.js 的文件,用于配置路由:

// 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;

/*
在上面的代码中,我们定义了两个路由
*/

3. 将路由添加到根实例

打开 main.js 文件,通常位于项目的根目录,然后将创建的路由添加到根 Vue 实例中:

// main.ts
import {createApp} from 'vue'
import App from './App.vue'
/* 引入路由 */
import router from './router/router'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'

createApp(App)
    .use(Antd)
    .use(router)
    .mount('#app')

4. 在组件中使用路由

在需要使用路由的组件中,你可以通过 <router-link> 标签来创建链接,通过 <router-view> 标签来显示对应的组件内容。

// App.vue

<template>
    <router-view></router-view>
</template>

<script>

    export default {
        name: 'App',
    }
</script>

<style>

</style>

<template>
    <div>
        <h1>Home Page</h1>
        <!-- 到 关于页面 -->
        <router-link to="/about">Go to About</router-link>
    </div>
</template>

其他应用

1. 部署到 Linux 中,配置 Nginx

// 首先,在 vue.config.ts 中设置 publicPath 选项
// 例如将 publicPath 设置为 ‘/bigscreen ’

// vue.config.ts
const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,
    publicPath: "/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')
Last Updated 3/6/2024, 10:02:39 AM