我們在前面的App.vue
例子中,有import Sidebar.vue
,因此載入完成後,畫面的顯示內容應該會在Sidebar.vue
中找到,因此我們順著路徑可以找到該檔案/src/components/Sidebar.vue
,並得到以下程式碼。
<!-- /src/components/Sidebar.vue -->
<template>
<BootstrapSidebar>
<!-- 導覽列 -->
<template v-slot:navbar>
<b-navbar>
<b-navbar-nav>
<b-nav-item />
<b-nav-item />
...
</b-navbar-nav>
</b-navbar>
</template>
<!-- 主要內容區 -->
<template v-slot:content>
<b-container>
<router-view />
</b-container>
</template>
</BootstrapSidebar>
</template>
可以看到<template>
之下主要有<BootstrapSidebar>
元件,這裡是使用外部元件,也就是別人寫好的現成的元件,但如何使用涉及其他安裝問題,在此先專注於畫面內容呈現部分。
有興趣者可先參考該元件撰寫者提供的資訊,https://www.npmjs.com/package/vue-bootstrap-sidebar
其中有兩個區塊,分別為導覽列,如navbar,及主要內容區,如content。導覽列通常會放置選項,供瀏覽者點選,並隨點選的項目,在主要內容區會有相對應的畫面呈現。
這裡就涉及到一個問題,即可以想像,每個選項對應的畫面應會不同,在Vue具體該如何呈現這些不同的畫面呢?這裡就要提到一個Vue router的工具,即在主要內容區中,所看到的<router-view />
。
所謂的<router-view />
,是Vue Router提供的內建套件,可根據所點選項的網址,以顯示對應的頁面組件。藉由路由設定檔來進行畫面的切換,該檔案通常放置於src/router/index.js
,參考如下。
// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
// 找到對應的組件(component),放置於 /src/views 中
import Login from "@/views/Login.vue";
import Employee from "@/views/Employee.vue";
// 設定路由,以配對各網址及其對應組件
const routes = [
{
path: "/",
redirect: "/login",
}, // 轉址設定:根路徑 / ,會轉址到 /login,代表首頁即登入頁
{
path: "/login",
name: "Login",
component: Login,
}, // 網址是 /login 時,就顯示Login.vue的畫面
{
path: "/employee",
name: "Employee",
component: Employee,
}, // 網址是 /employee 時,就顯示Employee.vue的畫面
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
接著,於src/main.js
中掛載router,參考如下
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 引入 Vue Router
const app = createApp(App);
app.use(router) // 掛載路由
app.mount('#app'); // 掛載到 index.html 的 <div id="app">
最後,Sidebar.vue中,在適當想要顯示內容的位置,放置<router-view />
的元件,路由設定就完成,後續畫面的顯示,將會隨著所點選項的網址而變動。
<!-- src/components/Sidebar.vue -->
<template>
<BootstrapSidebar>
<!-- 導覽列(略) -->
<!-- 主要內容區 -->
<template v-slot:content>
<b-container>
<!-- 放置路由設定元件 -->
<router-view />
</b-container>
</template>
</BootstrapSidebar>
</template>
彙整router顯示畫面的步驟及流程
<router-view />
的位置。index.html # 提供掛載點,如 <div id="app">
│
src/router/index.js # 路由根據設定,找到對應的組件畫面
│
main.js # Vue應用程式入口,如 createApp(App).use(router).mount('#app')
│
<router-view /> # 組件畫面在Sidebar.vue中的顯示位置
到此我們已經可以配置基本的網頁架構了,並將這些架構藉由router去配對網址,接下來的工作,就是針對各個組件畫面去撰寫,來豐富網頁的內容與功能。