Vue Router &&

Router

Vue Router

安裝 Vue Router

Vue Router installation
安裝指令

1
npm create vue@latest

路由

Step 1 建立路由與頁面
Step 2 引入 main.js
Step 3 src別名

Step 1 建立路由與頁面

  • 前置作業src建立router/index.js
  • src建立
    views/Home/index.vue
    views/AboutMe/index.vue
    views/errorPage/404.vue

src/router/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// src/router/index.js
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

const webTitle = "關於Lara || ";

const options = {
// history: createWebHashHistory(),
history: createWebHistory(),//井字號會不顯示
routes:[
{
path: '/',
name:'首頁',
component: () => import("@/views/Home/index.vue"),
meta:{title:webTitle+'首頁'}
},
{
path: '/about',
name:'關於我們',
component: () => import("@/views/AboutMe/index.vue"),
meta:{title:webTitle+'關於我們'}
},
{
path: '/:catchAll(.*)',
name: '404',
component: () => import('../views/errorPage/404.vue'),
meta: {
title:webTitle+'404'
},
}
],
}

const router = createRouter(options)
// 導航守衛
router.beforeEach( (to, from, next) => {
// webTitle
document.title = to.meta.title || webTitle + '首頁';
next();
})

// 輸出router
export default router
  • 每個頁面設定meta:{title:webTitle+'首頁'}
  • webTitle
    router.beforeEach => document.title;即是 webTitle;
    從導航守衛 改變webTitle: to.meta.title
#### views/Home/index.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div>
<div>{{ title }}</div>
</div>
</template>

<script setup>
import { ref } from "vue";
const title =ref('Home')
</script>

<style lang="scss" scoped>

</style>

views/AboutMe/index.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div>
<div>{{ title }}</div>
</div>
</template>

<script setup>
import {ref} from "vue";
const title =ref('About Me')
</script>

<style lang="scss" scoped>

</style>

views/errorPage/404.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div>
<h1>{{ title }}</h1>
<button @click="$router.push('/')">回首頁</button>
</div>
</template>


<script setup>
import { ref } from 'vue';
const title = ref('404');
</script>

Step 2 引入 main.js

1
2
3
4
5
6
7
8
9
import { createApp } from 'vue'
import './style.css'
+ import router from "./router/index";
import App from './App.vue'

const app = createApp(App)
+ app.use(router)
app.mount('#app')

Step 3 src別名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// vite.config.js
+ import { fileURLToPath, URL } from "node:url";
import { defineConfig } from 'vite'

import vue from '@vitejs/plugin-vue'


export default defineConfig(({ mode, command }) =>
{
console.log('目前模式', mode),
console.log('目前command',command)
return {
plugins: [
vue(),
],
// src別名
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},

}
});