Quasar 學習筆記 Ep 02 - Vue 與 Quasar 的路由介紹

Vue 與 Quasar 的路由介紹

在前一篇分享中,我分別使用 vue create 與 quasar create 內定選項建立了兩個專案,請保留這兩個專案,我們在後面的分享會用到。由 vue 建立的專案,是一個 SPA (Single Page Application),
而由Quasar 建立的專案,由於有 Drawer 選單,所以可以視為一個 MPA (Multiple Page Application) 多頁式應用程式。

如果是一個多頁式應用程式,我們該如何控制在不同的網頁中切換呢?就必須使用 Vue Router來控制。接下來,我就來介紹 Vue Router 的用法。

今天分享的內容會包含:
  1. 用 Vue CLI 建立一個多頁式應用程式
  2. Vue Router 介紹
  3. 以 Quasar CLI 建立一個多頁式應用程式
  4. Hash Mode 與 History Mode 的差異
  5. 新增 About, News 兩個子網頁

用 Vue 建立一個多頁式應用程式

先執行 power shell 或 cmd,進入 projects 目錄,在 cmd 中輸入 vue create hellovue2,但這次不要用 Default 選項,選擇手動。

Vue CLI v4.5.15
? Please pick a preset:
  Default ([Vue 2] babel, eslint)
  Default (Vue 3) ([Vue 3] babel, eslint) 
> Manually select features

按下 Enter 之後,會出現下面的選單:

Vue CLI v4.5.15
? Please pick a preset: Manually select features
? Check the features needed for your project: 
 (*) Choose Vue version
 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support        
>(*) Router
 ( ) Vuex
 ( ) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

選擇 Router 之後,接下來要選擇 3.x 版本,這很重要,而其餘的部分我們就都選擇 Default 值,產生一個樣板 Project。建立好 hellovue2 之後,執行下面的命令來執行。

 $ cd hellovue2
 $ npm run serve

執行結果如下:


馬上你就會發現,hellovue2 與 hellovue 的不同之處,就在於網頁的上方多了一個 Home | About 的選單列。

Vue Router 程式架構

為何我要先用 vue create 來建立一個 MPA project,這是因為 quasar 建立出來的樣版應用程式,會隱藏一些語法細節,對初學者而言,會搞不清前因後果。

Vue Router 的語法有兩個部分,我們要在網頁中加入 <router-view> 來定義路由的架構,然後使用 <router-link> 在網頁中產生使用者可以點選的連結。

以 Visual Studio Code 來開啟專案目錄,先看應用程式的起始點, main.js:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

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

程式中 import 了兩個東西,App.vue 與 ./router,所以接下來, App.vue 會被執行,./router 裡面的 index.js 也會被執行。這個原則跟網址類似,當網址沒有指定網頁時,index.html 就會被執行。

首先看 App.vue 這個根元件,開啟後馬上就可以看到下面的程式碼。

<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </div>
  <router-view/>
</template>

首先看 <div> 裡面的 <router-link>,這裡定義了 to="/" 根目錄網頁 Home 與 to="/About" 子目錄網頁 About,當我們輸入 http://localhost:8080/ 執行程式時, Home 就會出現,當點選 About 之後,上面的網址就會變成 http://localhost:8080/about。如果想要加一個 news 網頁,則在下面加入 <router-link to="/news">News</router-link> 即可 (別忘了補上 | 分隔符號)。往下馬上會看到 <router-view/>,即為程式渲染網頁內容的實際位置。

    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <router-link to="/news">News</router-link>

接著看 src/router 裡面的 index.js 檔案,看一下他的內容:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

這裡使用了兩種方式定義了兩個頁面,Pre-load 與 Lazy-Load,Home 網頁就是用 Pre-load 的方式,在程式一開始就先執行了 import Home from '../views/Home.vue' ,然後在 routes 常數裡面定義了三個屬性,path: '/', name: 'Home', component: Home 。但是 About 則用 Lazy-load 的方式,在定義 component 方法的時候,才 import(../views/About.vue)。

順著前面的舉例,如果我們要加一個 news 子網頁,加入以下程式碼:

  {
    path: '/news',
    name: 'News',
    component: () => import('../views/News.vue')
  }

在 ../views 目錄底下新增一個 News.vue 元件檔,並把 About.vue 的內容 copy 進去稍加修改:

<template>
  <div class="news">
    <h1>This is a news page</h1>
  </div>
</template>

全部儲存之後,程式會自動重新編譯,我們看一下執行結果:


Quasar 多頁應用程式

請開啟我們在 EP01中建立的 helloquasar project,直接在 cmd 輸入 quasar dev 看執行結果:


首先,跟剛才 Vue CLI 所建置的網頁第一個不同,就是原本 http://localhost:8080/ 網址變成了 http://localhost:8080/#/,這是因為 vue 有兩種處理前端路由的方式,分別是 Hash Mode 以及 History Mode,這是因為在 HTML5 還沒有出現之前,想要控制 URL 又不能前後換頁,就只能透過 Hash (#) 來達成。如果想換成 History Mode,可以開啟 quasar.conf.js,將第48行的 hash 改成 history 即可,如下圖:

    // Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-build
    build: {
      vueRouterMode: 'hash', // available values: 'hash', 'history'

 
我們先保留 Hash Mode,剛好熟悉其用法。要修改路由架構,不是從 src/router/index.js,而是從 src/router/routes.js 開始:

const routes = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/Index.vue') }
    ]
  },

Quasar 的路由定義成父子架構,父元件是 MainLayout.vue,定義了路由的框架,我們暫時不用改,子元件的根部元件 (path: ' ') 為 Index.vue ,就是首頁。打開 Index.vue,查看內容:

<template>
  <q-page class="flex flex-center">
    <img
      alt="Quasar logo"
      src="~assets/quasar-logo-vertical.svg"
      style="width: 200px; height: 200px"
    >
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'PageIndex'
})
</script>
 
範例非常簡單,就只顯示一個 Quasar Logo,我們在 <img> 下面加入說明文字:

<template>
  <q-page class="flex flex-center">
    <img
      alt="Quasar logo"
      src="~assets/quasar-logo-vertical.svg"
      style="width: 200px; height: 200px"
    >
    <h3>歡迎光臨網站首頁</h3>
    <p>
      Quasar是一款基於Vue.js開發的UI框架,可以讓你輕鬆構建網站簡潔明快的界面,
      更重要的是它還能讓你輕鬆做好RWD(響應式網站設計),除此之外還能幫助你加上PWA,
      使你的網頁變成手機上的App。
    </p>
  </q-page>
</template>

全部儲存之後看執行結果。


由於Quasar 支援響應式網頁,如果我們把瀏覽器縮小,就會看到以下的結果:


新增首頁以外的子網頁

接下來的任務,就是加上 About 以及 News 這兩個子網頁。首先,我們打開 routes.js,把 path: 'about' 以及 path: 'news' 這兩行加入,如下:

const routes = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/Index.vue') },
      { path: 'about', component: () => import('pages/About.vue') },
      { path: 'news', component: () => import('pages/News.vue') }
    ]
  },

既然多了兩個元件檔,請在 pages 目錄底下加入 About.vue 與 News.vue 這兩個元件檔,然後先把 Index.vue 的內容 Copy 進去,再稍加修改。

About.vue
<template>
  <q-page class="flex flex-center">
    <h3>關於這個網站</h3>
    <p>
      中央流行疫情指揮中心今(21)日表示,本(2021)年12月14日起入境擇定春節檢疫專案C方案之民眾,
      將自12月21日起陸續期滿168小時,凡經檢疫第6天PCR檢測陰性及返家居家檢疫環境與條件均符合規定者,
      請全程佩戴口罩,搭乘地方政府安排之防疫車輛,返家接續後7天在家居家檢疫,並配合以下檢測措施
    </p>
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'PageAbout'
})
</script>

News.vue
<template>
  <q-page class="flex flex-center">
    <h3>網站最新消息</h3>
    <p>
      指揮中心再次提醒,在居家檢疫期間,應留在家中,禁止外出,亦不得出境或出國,
      確實遵守「防範嚴重特殊傳染性肺炎入境健康聲明暨居家檢疫通知書(春節檢疫專案)」所載規定,
      並呼籲返家後7天係採1人1室之檢疫者,其同戶內同住者(非居家檢疫者)應共同遵守以下加強暨
      自主健康管理相關規定及檢測措施
    </p>
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'PageNews'
})
</script>

要顯示About網頁,請在瀏覽器中輸入 http://localhost:8080/#/about ,要顯示 News 網頁則是輸入 http://localhost:8080/#/news。頁面如下:


如果真的覺得 Hash (#) 很礙眼,可以將 quasar.conf.js 的設定改成 vueRouterMode: 'history' 即可。這樣瀏覽器中的網址就會改變。


本文就先分享到此,下篇文章就會分享最重要的部分,Drawer。

留言

這個網誌中的熱門文章

Python可以這樣玩(16):共陰/共陽七段顯示器

Python可以這樣玩(11):數學繪圖

Python可以這樣玩(15):蜂鳴器與音樂