wordpress_blog

This is a dynamic to static website.

Vue3 複習07

Vue Cli,整合性工具開發好容易

Vue Cli 介紹

為什麼要用 Vue Cli

  1. 前端開發日趨複雜,每個開發者習慣亦有很大不同,因此整合性的工具可減少彼此開發上的差異
  2. 編譯環境越來越複雜,缺乏整合工具將會在每次專案都耗去大量時間。
  3. 前後端分離形成主流,單頁式應用程式更符合開發習慣。
  4. 套件引用越來越多,導致難以管理。

Vue Cli 是什麼

  1. 基於 Webpack 所建置的開發工具
  2. 便於使用各種第三方套件 (BS4, Vue Router…)
  3. 可運行 Sass, Babel 等編譯工具
  4. 獨特 .vue 檔案,一次包含 html, js, css
  5. 便於開發 SPA 的網頁工具

基於 Webpack 開發的 Vue Cli

整合了哪些開發環境?

編譯各種語言使其可在瀏覽器上運行

程式碼品質檢視導入確保協作一致性

獨特 .vue 檔案開發 Vue 元件更為容易

關於 .vue 檔案

單一檔案同時包含 html, css, js 元件開發更一目了然

SPA 又是什麼?

原文為 single-page application,稱為單頁式應用程式

傳統的路由概念

傳統後端路由 https://www.hexschool.com/user

SPA 的優點

前端路由 https://www.hexschool.com/#/user

實現前後端分離

SPA 的優點

前端路由 https://www.hexschool.com/#/order

關於 Cli

原文為 Command-Line Interface,簡單來說就是命令列介面

Vue 同時提供 GUI 的介面

原文為 Graphical User Interface,簡單來說就是圖形使用者介面

  • 減少許多指令的記憶
  • 定義設定檔案
  • 進行狀態輕鬆檢視

讓我們來開始使用 Vue Cli 吧

準備流程:

  1. 安裝 Node.js
  2. 安裝 Vue Cli 全域環境
  3. 建立 Vue 專案
  4. 開始開發!

Vue Cli 章節資源

安裝 Node.js

參考 Gulp 課程,安裝流程的部分均可直接預覽(1-31-4)

Nodejs 官方網站連結

Vue Cli

英文中文

Vue Cli 4.x 同時可建立 Vue 2.x 及 Vue 3.x 的環境,無論你是要開發 2 or 3 都僅需要安裝當前版本的 Vue Cli 即可。

其他相關連結

以下為課程中會用到的相關連結

Vue RouterAxiosVue Axios

課程中運用到的指令

建立專案 vue create {{ 專案名稱 }}

運行 Vue 開發環境 npm run serve

編譯 Production 版本 npm run build

CLI 常用指令

通用指令(Mac, Windows 共用)

Nodejs 版本

node -v

npm 版本

npm -v

Windows 指令

回到資料夾頂端 cd\\

回到上一層 cd..

進入資料夾路徑 cd {{ 資料夾路徑 }}

中斷目前操作 ctrl + c

Mac OS 指令

回到資料夾頂端 cd \\

回到上一層 cd ..

進入資料夾路徑 cd {{ 資料夾路徑 }}

中斷目前操作 ctrl + c

安裝 Vue Cli 環境

// 終端機
// 全域環境
// node.js 是運行環境
node -v
// npm 是套件的管理工具
npm -v
// 安裝 Vue Cli
npm install -g @vue/cli
// 查詢 Vue Cli 版本
vue -V

建立專案

  1. 移動到指定資料夾位置
    cd {{ 資料夾路徑 }}
  2. 創建一個項目 vue create
    vue create new-project
  3. Please pick a preset: (Use arrow Keys)
    Manually select features
  4. Check the features needed for your project: Choose Vue version, Babel, Router, CSS Pre-processors, Linter
  5. Choose a version of Vue.js that you want to start the project with 3.x (Preview)
  6. Use history mode for router? (Requires proper server setup for index fallback in production) No
  7. Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
  8. Pick a linter / formatter config: Airbnb
  9. Pick additional lint features: Lint on save
  10. Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
  11. Save this as a preset for future projects? (y/N) n

打開專案

  1. 使用 VSCode 開啟專案
  2. Ctrl + ` 打開終端機
  3. 使用 npm run serve 運行環境
  4. 點擊連結開啟網頁
// 常用 NVM 指令
// 常見指令:
// nvm ls-remote: 列出目前可用的遠端 Node.js 版本
// nvm install: 安裝特定版本的 Node.js
// nvm ls: 列出本地端所安裝的 Node.js 環境
// nvm alias default node: 設定命令列預設開啟的 Node.js 版本
// nvm use: 當前命令列套用特定版本的 Node.js

Vue Cli 環境中的檔案說明

從下往上說明

  • README.md – 介紹的檔案
  • package.json – 專案的配置檔案
    • “scripts” – 指令
      執行指令,npm run serve、”serve” 滑鼠點擊 Run Script
  • package-lock.json – 實際安裝的套件版本以及相關描述
  • babel.config.js – babel 設定檔案
  • .gitignore – 在 git 忽略的檔案
  • .eslintrc.js – eslint 設定檔案
    依據選擇把設定檔以及延伸的規則載入
  • .editorconfig – 編輯器設定檔
  • .browserslistrc – 預期要支援的版本
  • src – 在這個專案中最重要的一個資料夾
    • main.js – 整個專案的進入點
  • App.vue – 在 main.js 第一個生成的主要元件
    通常只是做簡單的配置
  • views – 主要的頁面會放在這個資料夾內
  • router – 路由表放在 router 資料夾 index.js 檔案裡面
  • components – 掛載的子元件會放在 components 資料夾內
  • assets – 相關的一些其他資產
    例如: 比較小的圖片、CSS、JS 檔案都可以放在這個資料夾內
  • public – 原則上是跟進入點沒有相關聯的檔案、不需要編譯的檔案
    index.html,主要在 Vue 的元件生成之後要掛載在一個實體的頁面上所需要的檔案 (在 public 資料夾內唯一會編譯的檔案)
    比較大的圖片或其他資源也可以放在 public 資料夾內
  • node_modules – 運行所需要的延伸套件
    依據 package.json 檔案所列的清單安裝

指令太麻煩,來試試看 GUI 吧

建立專案

  1. 指令 vue ui
  2. 在 Vue 專案管理器按下新增
  3. 選擇專案路徑
  4. 在此新增專案
  5. 新增新專案
    • 專案資料夾 gui-demo
    • 包管理器 npm
    • Git 倉庫 初始化 git 倉庫(建議)
  6. 模板
    選擇一套模板 – 手動
  7. 功能
    Choose Vue version、Babel、Router、CSS Pre-processors、Linter / Formatter
  8. 設定
    • Choose a version of Vue.js that you want to start the project with – 3.x (Preview)
    • Use history mode for router? (Requires proper server setup for index fallback in production) – No
    • Pick a CSS pr-processor: Sass/SCSS (with node-sass)
    • Pick a linter / formatter config: ESLint + Airbnb config
    • Pick additional lint features: Lint on save
  9. 保存為新模板 – 新增專案,不保存預設

專案控制台

  • 插件 – 加入新的 Vue CLI 插件
  • 依賴 – 是用來管理包 (package)
  • 設定 – 可以設定工具
  • 任務 – 可以執行腳本 (例如 webpack)
    serve 編譯和熱更新 (用於開發環境)
    build 編譯並壓縮 (用於生產環境)

如何在 Cli 環境中加入 Vue 元件

  1. 安裝 Bootstrap 套件
    終止終端機 – Ctrl + c,輸入 npm install bootstrap@5.3.3 安裝
  2. 重新運行 npm run serve
  3. 把 App.vue 檔案預設 CSS 樣式清除
    匯入外部套件 – @import “bootstrap”;
    載入 Bootstrap 元件測試
  4. 新增元件加到 About 頁面
    到 Bootstrap Card 元件複製相對簡單的程式碼
  5. 新增的元件會放在 components 資料夾內
    獨立的頁面會放在 views 資料夾內
  6. 在 components 資料夾內新增一個檔案 Card.vue
    命名通常會使用開頭字母大寫的形式
    使用 <template> 標籤把 Bootstrap Card 元件程式碼貼上
  7. 在 About.vue 加入卡片元件
  8. 在 Card.vue 加入 data
// App.vue
<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </div>
  <router-view />
  <button type="button" class="btn btn-primary">Primary</button>
</template>

<style lang="scss">
@import "bootstrap";
</style>
// Card.vue
<template>
  <div class="card" style="width: 18rem">
    <div class="card-body">
      <h5 class="card-title">{{ title }}</h5>
      <h6 class="card-subtitle mb-2 text-body-secondary">Card subtitle</h6>
      <p class="card-text">
        Some quick example text to build on the card title and make up the bulk of the card's
        content.
      </p>
      <a href="#" class="card-link">Card link</a>
      <a href="#" class="card-link">Another link</a>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: '這是一段標題',
    };
  },
};
</script>
// About.vue
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <!-- 7-4. Card 呈現在畫面上 -->
    <Card></Card>
  </div>
</template>

<script>
// 7-2. 外部元件匯入進來
import Card from '@/components/Card.vue';

// 7-1. 元件 js 匯出
export default {
  // 7-3. 區域註冊
  components: {
    Card,
  },
};
</script>

Cli 中引入外部套件

VeeValidate

Getting Started – Using a package manager

Global Validators / @vee-validate/rules

Localization (i18n) / Using @vee-validate/i18n

  1. 安裝 VeeValidate 套件
  2. 總共有三個套件必須要安裝
    npm i vee-validate @vee-validate/rules @vee-validate/i18n –save
  3. main.js 是 webpack 的主要進入點
    外部資源匯入可以撰寫到 main.js 裡面
  4. 匯入 vee-validate 主套件、相關規則、多國語系的功能
    import { Field, Form, ErrorMessage, defineRule, configure, } from ‘vee-validate’;
    import { required, email, min } from ‘@vee-validate/rules’;
    import { localize, setLocale } from ‘@vee-validate/i18n’;
  5. 基本設定
    defineRule(‘required’, required);
    defineRule(’email’, email);
    defineRule(‘min’, min);
    configure({
    generateMessage: localize({ zh_TW: zhTW }),
    validateOnInput: true,
    });
    setLocale(‘zh_TW’);
  6. 匯入繁體中文語系檔案
    import zhTW from ‘@vee-validate/i18n/dist/locale/zh_TW.json’;
  7. 註冊元件- 程式碼改寫,註冊 Form, Field, ErrorMessage 元件
    const app = createApp(App).use(router);
    app.component(‘Form’, Form);
    app.component(‘Field’, Field);
    app.component(‘ErrorMessage’, ErrorMessage);

    app.mount(‘#app’);
  8. 重新運行 npm run serve
  9. 表單驗證的表單加到畫面上加到 Home.vue <template> 標籤內,
    並在 script 加上一些內容
// main.js
import { createApp } from 'vue';

// 匯入 vee-validate 主套件
import {
  Field, Form, ErrorMessage, defineRule, configure,
} from 'vee-validate';
// 匯入 vee-validate 相關規則
import { required, email, min } from '@vee-validate/rules';
// 匯入多國語系的功能
import { localize, setLocale } from '@vee-validate/i18n';
// 匯入繁體中文語系檔案
import zhTW from '@vee-validate/i18n/dist/locale/zh_TW.json';

import App from './App.vue';
import router from './router';

// 定義驗證規則
defineRule('required', required);
defineRule('email', email);
defineRule('min', min);
// 設定 vee-validate 全域規則
configure({
  generateMessage: localize({ zh_TW: zhTW }), // 載入繁體中文語系
  validateOnInput: true, // 當輸入任何內容直接進行驗證
});
// 設定預設語系
setLocale('zh_TW');

const app = createApp(App).use(router);
// 註冊 vee-validate 三個全域元件
app.component('Form', Form);
app.component('Field', Field);
app.component('ErrorMessage', ErrorMessage);

app.mount('#app');
// Home.vue
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <Form v-slot="{ errors, values, validate }" @submit="onSubmit">
      {{ errors }} {{ values }}
      <div class="mb-3">
        <label for="email" class="form-label">Email</label>
        <Field id="email" name="email" type="email"
        class="form-control" :class="{ 'is-invalid': errors['email'] }"
        placeholder="請輸入 Email" rules="email|required" v-model="user.email"></Field>
        <error-message name="email" class="invalid-feedback"></error-message>
      </div>
      <button class="btn me-2 btn-outline-primary" type="button" @click="validate">驗證</button>
      <button class="btn btn-primary" type="submit">Submit</button>
    </Form>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue';

export default {
  name: 'Home',
  components: {
    HelloWorld,
  },
  data() {
    return {
      user: {},
    };
  },
  methods: {
    onSubmit() {
      console.log(this.user);
    },
  },
  created() {
    console.log(this);
  },
};
</script>

Vue Cli 中 VeeValidate 範例程式碼

// main.js
import { createApp } from 'vue';

// 匯入 vee-validate 主套件
import {
  Field, Form, ErrorMessage, defineRule, configure,
} from 'vee-validate';
// 匯入 vee-validate 相關規則
import { required, email, min } from '@vee-validate/rules';
// 匯入多國語系的功能
import { localize, setLocale } from '@vee-validate/i18n';
// 匯入繁體中文語系檔案
import zhTW from '@vee-validate/i18n/dist/locale/zh_TW.json';

import App from './App.vue';
import router from './router';

// 定義驗證規則
defineRule('required', required);
defineRule('email', email);
defineRule('min', min);
// 設定 vee-validate 全域規則
configure({
  generateMessage: localize({ zh_TW: zhTW }), // 載入繁體中文語系
  validateOnInput: true, // 當輸入任何內容直接進行驗證
});
// 設定預設語系
setLocale('zh_TW');

const app = createApp(App).use(router);
// 註冊 vee-validate 三個全域元件
app.component('Form', Form);
app.component('Field', Field);
app.component('ErrorMessage', ErrorMessage);

app.mount('#app');
// Home.vue
<template>
  <div class="home">
    <Form v-slot="{ errors, values, validate }" @submit="onSubmit">
      {{ errors }} {{ values }}
      <div class="mb-3">
        <label for="email" class="form-label">Email</label>
        <Field id="email" name="email" type="email"
        class="form-control" :class="{ 'is-invalid': errors['email'] }"
        placeholder="請輸入 Email" rules="email|required" v-model="user.email"></Field>
        <error-message name="email" class="invalid-feedback"></error-message>
      </div>
      <button class="btn me-2 btn-outline-primary" type="button" @click="validate">驗證</button>
      <button class="btn btn-primary" type="submit">Submit</button>
    </Form>
  </div>
</template>

<script>

export default {
  name: 'Home',
  data() {
    return {
      user: {},
    };
  },
  methods: {
    onSubmit() {
      console.log(this.user);
    },
  },
  created() {
    console.log(this);
  },
};
</script>

Vue Cli 中環境變數基礎觀念

環境變數簡單區分為,development 開發者環境、production 正式環境。

建立環境變數流程

  1. 在專案資料夾新增 .env 檔案
    VUE_APP_NAME=小明的家
  2. 在 APP.vue 加上 <script> 程式碼
  3. 使用 {{ name }} 方式把 name 呈現到畫面上
  4. 調整環境變數後需重新運行 npm run serve
// .env
VUE_APP_NAME=小明的家
// App.vue
<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </div>
  <router-view />
  {{ name }}
  <button type="button" class="btn btn-primary">Primary</button>
</template>

<script>
export default {
  data() {
    return {
      name: process.env.VUE_APP_NAME,
    };
  },
};
</script>

<style lang="scss">
@import "bootstrap";
</style>

Vue Cli 編譯設定檔

  1. 編譯專案 – npm run build
    編譯完成後會產生 dist 資料夾
  2. dist/index.html 檔案路徑是使用絕對路徑的方式進行撰寫,沒有透過 web server 的形式是沒辦法瀏覽
  3. 用 VSCode 把 dist 資料夾打開,使用 Go Live 打開
  4. 複製 .env 檔案改為 .env.production 檔案名稱
  5. 修改 .env.production 檔案內容
    VUE_APP_NAME=老闆的家
    重新編譯檔案 npm run build
  6. 再用 VSCode 把 dist 資料夾打開,使用 Go Live 打開
    小明的家就變成老闆的家
    環境變數在使用 production 之後的差異
// .env.production
VUE_APP_NAME=老闆的家

調整編譯後的路徑

  1. 新增 vue.config.js 檔案
    建議直接使用 vue ui 建立 vue.config.js
  2. 在專案終端機輸入 vue ui
    透過這種方式就不需要記太多的參數,就可以直接透過介面的形式來調整參數
  3. 設定 > Vue CLI > 公開路徑
    公開路徑: /dist/,保存修改後就產生 vue.config.js 檔案
  4. 重新編譯專案 – npm run build
    dist 路徑就可以直接在當前的專案下直接使用 web serve 的形式打開
  5. 直接選用 dist/index 檔案使用 Go Live 打開

哪些情況必須調整路徑

  • 專案完成後把專案交給後端部署的時候
  • 完成課程最終作業部屬部署到 GitHub Pages

GitHub Pages 是一個免費的網頁空間,適合放置靜態網站。Vue Cli 編譯後的檔案就是屬於靜態網頁。

Github Pages 教學連結

修正公開路徑: /專案資料夾名稱/dist/