Skip to content

2. Vue.js 入门

2.1. 示例 01:Vue.js 应用的结构

2.1.1. package.json 文件

examples 文件夹中的 [package.json] 文件声明了所用的库和项目命令:

{
  "name": "examples-vuejs",
  "version": "1.0.0",
  "description": "The small examples of the course [Step-by-step introduction to the Vue.js framework] - a single installation for all of them",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "check": "vue-tsc --noEmit"
  },
  "dependencies": {
    "bootstrap": "^5.3.8",
    "pinia": "^3.0.4",
    "vue": "^3.5.22",
    "vue-i18n": "~11.3.2",
    "vue-router": "^4.6.3"
  },
  "devDependencies": {
    "@types/node": "^22.10.0",
    "@vitejs/plugin-vue": "^6.0.1",
    "@vue/tsconfig": "^0.8.1",
    "typescript": "~5.9.3",
    "vite": "^7.1.12",
    "vue-tsc": "^3.1.3"
  }
}

我们来逐段看这个文件:

  • 第 6 行:项目中的 [JavaScript] 文件是 ES 模块 ([import] / [export]),这是 [JavaScript] 的标准格式,浏览器和 [Node.js] 都支持它;
  • 第 7–11 行:项目命令,通过 [npm run <name>] 启动:
    • [npm run dev] 启动 [Vite] 的开发服务器;
    • [npm run check] 通过 [TypeScript] 工具 [vue-tsc] 检查所有文件(包括 [.vue] 文件)的类型;
    • [npm run build] 先检查类型,然后构建示例的生产版本;
  • 第 12–18 行:应用 在浏览器中所需的库:[Vue.js] 本身、它的路由器([vue-router])、用于共享状态的 [Pinia] 、用于多语言的 [vue-i18n] ,以及用于排版样式的 [Bootstrap] ;
  • 第 19–26 行:开发工具:[Vite] 及其用于 [.vue] 文件的扩展、编译器 [TypeScript],以及 [vue-tsc]。它们不属于交付给用户的应用。

版本号前缀 [^] ([^3.5.22])允许 [npm] 安装同一主版本(3.x.y)的更新版本;前缀 [~] ([~11.3.2])只允许热修复版本(11.3.x)。[vue-i18n] 的版本被有意锁定在 11.3 系列:之后的版本需要 [Node.js] 22。

2.1.2. vite.config.ts 文件

[Vite] 是在开发期间运行 [Vue.js] 应用、并在随后为生产环境构建它的工具。它的配置对所有示例通用:

// =========================================================================
// vite.config.ts - 所有示例共用的 Vite 配置。
// -------------------------------------------------------------------------
// Vite 既是:
//   - 开发服务器(npm run dev):它会即时编译浏览器请求的
//     .vue 和 .ts 文件,并在每次保存时重新加载页面
//     (或只重新加载被修改的组件);
//   - 构建工具(npm run build):它会在 dist/ 中生成
//     经过优化的 .js 和 .css 文件,用于放到 Web 服务器上。
//
// 每个示例都是一个独立的小应用,有自己的
// index.html:01-first-application/index.html、02-reactivity/index.html……
// 一个 Vite 服务器为它们全部提供服务:http://localhost:5173/ 显示
// 目录(本文件夹的 index.html),http://localhost:5173/01-first-application/
// 显示第一个示例,依此类推。
// =========================================================================

import { existsSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { resolve } from 'node:path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

const root = fileURLToPath(new URL('.', import.meta.url));

// 示例文件夹:名称以两位数字开头的文件夹
const examples = readdirSync(root).filter((d) => /^\d\d-/.test(d) && existsSync(resolve(root, d, 'index.html')));

export default defineConfig({
  // 教会 Vite 如何编译 .vue 文件的插件
  plugins: [vue()],

  server: {
    port: 5173,
    // 代理:浏览器发往 /api/... 的任何请求都会由
    // Vite 转发给 RdvMedecins JSON 服务器(8080 端口),然后响应再返回
    // 浏览器。对浏览器而言,页面和 API 因此具有相同的源
    // (http://localhost:5173):无需配置 CORS,并且 JWT 令牌的
    // Cookie 也能正常传递(见黑盒一章)。
    proxy: {
      '/api': 'http://localhost:8080',
    },
  },

  // npm run build:每个示例一个 HTML 入口页面,外加目录页
  build: {
    rollupOptions: {
      input: Object.fromEntries([
        ['contents', resolve(root, 'index.html')],
        ...examples.map((d) => [d, resolve(root, d, 'index.html')]),
      ]),
    },
  },
});
  • 第 31 行:指示 [Vite] 编译 [.vue] 文件的扩展。浏览器无法读取 [.vue] 文件:当浏览器请求这样的文件时,[Vite] 会即时将其转换为标准的 [JavaScript] 文件;
  • 第 34 行:开发服务器的端口;
  • 第 40–41 行:代理,从示例 17 开始才会用到:浏览器发往以 [/api] 开头的地址的任何请求,都会被转发到 [RdvMedecins] JSON 服务器的 8080 端口。我们稍后会回到这一点;
  • 第 27 行和第 46–53 行:[npm run build] 必须知道应用的所有入口页面。为它提供索引,以及名称以两位数字开头的每个文件夹中的 [index.html] 文件。

2.1.3. tsconfig.json 和 env.d.ts 文件

1
2
3
4
5
6
7
8
9
{
  "extends": "@vue/tsconfig/tsconfig.dom.json",
  "compilerOptions": {
    "types": ["vite/client"],
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "include": ["*/src/**/*.ts", "*/src/**/*.vue", "common/**/*.ts", "common/**/*.vue", "env.d.ts"]
}
  • 第 2 行:我们使用为 [TypeScript] 推荐的、适用于 [Vue.js] 的配置([@vue/tsconfig] 包):现代代码、严格模式、浏览器(DOM)类型检查;
  • 第 4 行:[Vite] 特有的类型(例如导入 [.css] 或 [.svg] 文件时);
  • 第 5–7 行:未使用的变量或参数会被报告为错误;
  • 第 8 行:需要检查的文件:示例的 [src] 文件夹以及 [common] 文件夹中的文件。

文件 [env.d.ts] 只包含一条指令,它让编辑器能够识别与 [Vite] 相同的类型:

// Vite 特有的类型(导入 .css 文件、import.meta.env 等)
/// <reference types="vite/client" />

2.1.4. index.html 页面

每个示例都有自己的 HTML 页面。示例 01 的页面:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example 01 - a first application</title>
</head>
<body>
  <!-- Vue.js 应用显示在这个元素中(见 src/main.ts) -->
  <div id="app"></div>
  <script type="module" src="./src/main.ts"></script>
</body>
</html>

这是浏览器将要加载的唯一页面。它几乎是空的:

  • 第 10 行:[Vue.js] 将在其中显示应用的元素;
  • 第 11 行:应用程序。[Vite] 编译它,并以 [JavaScript] 的形式发送给浏览器。

2.1.5. 入口点:main.ts

// =========================================================================
// 01-first-application/src/main.ts - 应用的入口点
// -------------------------------------------------------------------------
// index.html 会加载这个文件(<script type="module" src="./src/main.ts">)。
// 它根据根组件(App.vue)构建 Vue.js 应用,
// 并把它显示在页面的 <div id="app"> 元素中。
// =========================================================================

import { createApp } from 'vue';
// Bootstrap 样式表:Vite 会把它插入页面
import 'bootstrap/dist/css/bootstrap.min.css';
import App from './App.vue';

// createApp(App):一个以 App 为根组件的应用;
// mount('#app'):它渲染出的 HTML 会替换 <div id="app"> 的内容
createApp(App).mount('#app');
  • 第 9 行:[Vue.js] 中创建应用的函数;
  • 第 11 行:样式表 [CSS] 像模块一样被导入。[Vite] 会把它插入页面;
  • 第 12 行:应用的 根组件,定义在文件 [App.vue] 中;
  • 第 16 行:应用由该组件创建,然后“挂载”到 [<div id="app">] 元素中:由 [App.vue] 生成的 HTML 会替换该元素的内容。

2.1.6. 根组件:App.vue

<!--
  =========================================================================
  01-first-application/src/App.vue - a first component
  -------------------------------------------------------------------------
  A .vue file (Single File Component) groups the three facets of a
  component:
    - <script setup>: the data and the code of the component (TypeScript);
    - <template>    : the HTML to display, with {{ ... }};
    - <style>       : its CSS (here "scoped": it only applies to it).
  =========================================================================
-->
<script setup lang="ts">
import { ref } from 'vue';

// “普通”数据:模板可以显示它
const title = 'Welcome to Vue.js';
const languages = ['TypeScript', 'HTML', 'CSS'];

// ref(...):一个响应式数据。当它的值(.value)变化时,Vue
// 会自动更新页面上显示它的位置
const counter = ref(0);
const time = ref(new Date().toLocaleTimeString());

// 由模板中的按钮调用的函数
function increment(): void {
  counter.value++;
  time.value = new Date().toLocaleTimeString();
}
</script>

<template>
  <div class="container py-4">
    <!-- {{ expression }}:表达式的值,被插入页面 -->
    <h1 class="h3">{{ title }}</h1>
    <p>This page is built in the browser, by Vue.js, from three files: index.html, main.ts and App.vue.</p>
    <p>It is written in {{ languages.join(', ') }} ({{ languages.length }} languages).</p>

    <!-- @click:点击时要调用的函数(见示例 04) -->
    <button class="btn btn-primary" @click="increment">Click me</button>
    <!-- 在模板中不需要 .value:Vue 会自动“解包”ref -->
    <p class="mt-3 counter">You clicked {{ counter }} times (last click: {{ time }}).</p>
  </div>
</template>

<style scoped>
/* "scoped":这条规则只作用于本组件的元素 */
.counter {
  font-weight: bold;
  color: #0d6efd;
}
</style>

一个 [.vue] 文件(单文件组件,简称 SFC)整合了组件的三个方面:

  • 第 12–29 行:组件的 代码,使用 [TypeScript] ([lang="ts"])。有了 [setup],脚本顶层声明的所有变量和函数都可以直接在模板中使用;
    • 第 16–17 行:两个普通数据项;
    • 第 21 行:[ref(0)] 创建一个初始值为 0 的 响应式数据项。它的值通过属性 [value] 读取和修改。当它变化时,[Vue.js] 会更新页面上所有显示它的位置;
    • 第 25–27 行:一个修改两个响应式数据项的函数。它不会改动页面:[Vue.js] 会去更新页面;
  • 第 31–43 行:组件的 HTML:
    • 第 34 行:[{{ expression }}] 语法(“双花括号”)把一个 [TypeScript] 表达式的值插入页面。它会被 转义:如果 [title] 包含 [<b>],则 [<b>] 会被原样显示,而不会把该标签解释为标签;
    • 第 36 行:表达式可以是任何内容:方法调用、计算;
    • 第 39 行:点击按钮会调用函数 [increment] (见示例 04);
    • 第 41 行:在模板中,写的是 [counter],而不是 [counter.value]:[Vue.js] 会自动“解包”[ref];
  • 第 45–51 行:组件的 CSS。有了 [scoped],其规则只作用于该组件的元素:[Vite] 会给这些元素添加一个唯一属性([data-v-xxxx]),并把它加入选择器中。

2.1.7. 运行

在 [Vite] 服务器运行时([npm run dev]),打开 URL http://localhost:5173/01-first-application/ 并点击按钮三次:

Image

可以尝试两个小实验:

  • 在 [App.vue] 中编辑标题文本并保存文件:页面会立即更新,无需重新加载,并且计数器保持其值。这就是 模块热替换 (HMR,[Hot Module Replacement]),由 [Vite] 提供;
  • 查看页面的源代码(Ctrl-U):它只包含页面 [index.html],而它几乎是空的。显示出来的 HTML 是由 [Vue.js] 在浏览器中生成的。要查看它,请使用开发者工具的检查器(F12,Elements 选项卡)或扩展 [Vue.js devtools],后者还会显示组件及其数据。

2.2. 示例 02:响应式

响应式是 [Vue.js] 的核心。本示例计算一件商品的含税价格:

<!--
  =========================================================================
  02-reactivity/src/App.vue - ref, reactive, computed, watch
  -------------------------------------------------------------------------
  A small calculator of prices including VAT:
    - ref      : a simple reactive value (a number, a string...);
    - reactive : a reactive OBJECT (all its properties are reactive);
    - computed : a value COMPUTED from other ones, recomputed
                 automatically when they change;
    - watch    : code executed when a value changes (an "effect").
  =========================================================================
-->
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';

// ref:它的值通过 .value 读取和写入(在 TypeScript 代码中)
const quantity = ref(1);

// reactive:一个对象,其属性可以直接读取和写入
const item = reactive({
  label: 'Pen',
  priceExclVat: 2.5,
  vatRate: 20, // 以 % 为单位
});

// computed:从不直接赋值,总是重新计算。Vue 知道它依赖哪些
// 数据(quantity、item.priceExclVat、item.vatRate):
// 当其中任何一个变化时才重新计算,并且仅在此时重新计算
const totalExclVat = computed(() => quantity.value * item.priceExclVat);
const vatAmount = computed(() => (totalExclVat.value * item.vatRate) / 100);
const totalInclVat = computed(() => totalExclVat.value + vatAmount.value);

// 欧元金额格式化器,英语风格(€1,234.50)
const euros = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'EUR' });

// watch:含税总额每次变化时,我们都会留下一条记录
const history = ref<string[]>([]);
watch(totalInclVat, (newValue, oldValue) => {
  history.value.unshift(`${euros.format(oldValue)} -> ${euros.format(newValue)}`);
  history.value = history.value.slice(0, 5); // 最近的 5 条
});

function reset(): void {
  quantity.value = 1;
  item.priceExclVat = 2.5;
  item.vatRate = 20;
}
</script>

<template>
  <div class="container py-4">
    <h1 class="h3 mb-3">Example 02 - reactivity</h1>
    <div class="row g-4">
      <div class="col-md-6">
        <div class="card p-3">
          <!-- v-model 把字段与一项数据双向关联(见示例 05) -->
          <label class="form-label">Item</label>
          <input v-model="item.label" class="form-control mb-2">
          <label class="form-label">Unit price excl. VAT</label>
          <input v-model.number="item.priceExclVat" type="number" step="0.1" min="0" class="form-control mb-2">
          <label class="form-label">Quantity</label>
          <input v-model.number="quantity" type="number" min="0" class="form-control mb-2">
          <label class="form-label">VAT rate</label>
          <select v-model.number="item.vatRate" class="form-select mb-3">
            <option :value="5.5">5.5 %</option>
            <option :value="10">10 %</option>
            <option :value="20">20 %</option>
          </select>
          <button class="btn btn-outline-secondary" @click="reset">Reset</button>
        </div>
      </div>
      <div class="col-md-6">
        <div class="card p-3">
          <h2 class="h5">{{ quantity }} x {{ item.label }}</h2>
          <table class="table mb-0">
            <tbody>
              <tr><td>Total excl. VAT</td><td class="text-end">{{ euros.format(totalExclVat) }}</td></tr>
              <tr><td>VAT ({{ item.vatRate }} %)</td><td class="text-end">{{ euros.format(vatAmount) }}</td></tr>
              <tr class="fw-bold"><td>Total incl. VAT</td><td class="text-end">{{ euros.format(totalInclVat) }}</td></tr>
            </tbody>
          </table>
        </div>
        <div class="card p-3 mt-3">
          <h2 class="h6">History of the total incl. VAT (watch)</h2>
          <ul class="mb-0">
            <li v-for="(line, i) in history" :key="i">{{ line }}</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
  • 第 17 行:[ref] 接受简单值(数字、字符串、布尔值);
  • 第 20–24 行:[reactive] 使整个 对象 变为响应式:它的每个属性都是响应式的。可以直接读写它们([item.priceExclVat]),无需 [.value];
  • 第 29–31 行:[computed] 定义一个由其他值 计算得出的 值。[Vue.js] 会记录计算过程中读取的数据([quantity]、[item.priceExclVat]...),并且只在其中某个数据变化时才重新计算。永远不要给它赋值:只能读取它([totalExclVat.value]);
  • 第 34 行:[Intl.NumberFormat],[JavaScript] 内置的数字格式化工具:[2.5] 会变成“€2.50”;
  • 第 38–41 行:每当数据变化时,[watch] 就会执行代码,并同时接收新值和旧值。它用于 动作 ,例如保存数据、发送请求或写入浏览器的存储……要 显示 派生值,我们更倾向于使用 [computed];
  • 第 43–46 行:只需修改数据;所有字段、合计和历史记录都会随之更新;
  • 第 58–64 行:[v-model] 把每个字段与一个数据项双向关联(见示例 05);
  • 第 77 行:在模板中,[computed] 的用法与 [ref] 相同,无需 [.value];
  • 第 86 行:对 [history] 数组的每个元素重复生成的列表(见示例 03)。

Image

2.3. 示例 03:指令

指令 是一种特殊的模板属性,以 [v-] 为前缀,用于定义其所作用元素的行为。

<!--
  =========================================================================
  03-directives/src/App.vue - the basic directives
  -------------------------------------------------------------------------
  A DIRECTIVE is a special attribute of the template, prefixed by v-:
    - v-bind:attr="expr" (short form :attr="expr"): the value of an HTML
      attribute computed by an expression; :class and :style accept
      objects and arrays;
    - v-if / v-else-if / v-else: the element only exists in the page if
      the condition is true;
    - v-show: the element always exists, it is only hidden (display:none);
    - v-for="x in list": the element is repeated for each x, with a
      unique :key that allows Vue to follow each row.
  =========================================================================
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
// 导入图片:Vite 提供它的 URL(在生产环境中,则提供
// 带唯一名称的文件优化副本)
import logoUrl from './assets/doctor.svg';

// 一个 TypeScript 接口描述列表中对象的结构
interface Doctor {
  id: number;
  title: string;
  firstName: string;
  lastName: string;
  specialty: string;
  available: boolean;
}

const doctors = ref<Doctor[]>([
  { id: 1, title: 'Mme', firstName: 'Marie', lastName: 'PELISSIER', specialty: 'general practitioner', available: true },
  { id: 2, title: 'Mr', firstName: 'Paul', lastName: 'TATOU', specialty: 'pediatrician', available: false },
  { id: 3, title: 'Melle', firstName: 'Sophie', lastName: 'DUPONT', specialty: 'general practitioner', available: true },
]);

const filter = ref(''); // 搜索的文本
const onlyAvailable = ref(false);
const showHelp = ref(true);

// 显示的列表:一个 computed,在过滤条件变化时重新计算
const displayedDoctors = computed(() =>
  doctors.value.filter(
    (m) =>
      (!onlyAvailable.value || m.available) &&
      `${m.firstName} ${m.lastName} ${m.specialty}`.toLowerCase().includes(filter.value.trim().toLowerCase()),
  ),
);
</script>

<template>
  <div class="container py-4">
    <h1 class="h3 mb-3">
      <!-- :src:src 属性的值就是变量 logoUrl 的值 -->
      <img :src="logoUrl" alt="logo" width="32" height="32">
      Example 03 - directives
    </h1>

    <div class="d-flex flex-wrap gap-3 align-items-center mb-3">
      <input v-model="filter" class="form-control w-auto" placeholder="search...">
      <label class="form-check-label">
        <input v-model="onlyAvailable" type="checkbox" class="form-check-input"> available only
      </label>
      <button class="btn btn-sm btn-outline-secondary" @click="showHelp = !showHelp">
        {{ showHelp ? "Hide help" : "Show help" }}
      </button>
    </div>

    <!-- v-show:该段落仍留在页面中,只是被隐藏 -->
    <p v-show="showHelp" class="alert alert-info">
      Type a name or a specialty. Unavailable doctors are greyed out.
    </p>

    <!-- v-if / v-else-if / v-else:三个块中同一时刻只存在一个 -->
    <p v-if="doctors.length === 0" class="text-muted">No doctors.</p>
    <p v-else-if="displayedDoctors.length === 0" class="text-warning">No doctor matches "{{ filter }}".</p>
    <table v-else class="table">
      <thead>
        <tr><th>#</th><th>Doctor</th><th>Specialty</th><th>Status</th></tr>
      </thead>
      <tbody>
        <!-- v-for: one row per doctor; (m, index) also gives the rank.
             :key="m.id": the identity of each row, so that Vue knows
             which row to add, move or remove when the list changes -->
        <tr v-for="(m, index) in displayedDoctors" :key="m.id" :class="{ 'text-muted': !m.available }">
          <td>{{ index + 1 }}</td>
          <td>{{ m.title }} {{ m.firstName }} {{ m.lastName }}</td>
          <td>{{ m.specialty }}</td>
          <td>
            <!-- 带数组的 :class:多个类,其中一个是计算得出的 -->
            <span :class="['badge', m.available ? 'text-bg-success' : 'text-bg-secondary']">
              {{ m.available ? 'available' : 'unavailable' }}
            </span>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 带对象的 :style:计算得出的 CSS 属性 -->
    <p :style="{ fontSize: 12 + displayedDoctors.length * 2 + 'px' }">
      {{ displayedDoctors.length }} doctor(s) displayed - the size of this text depends on it.
    </p>
  </div>
</template>
  • 第 23 行:一个 [TypeScript] 接口描述列表中对象的格式;[ref<Doctor[]>(...)] 指定数据类型;
  • 第 20 行:图片作为模块导入。[Vite] 提供它的地址;在生产环境中,它会创建一个带唯一名称的副本(名称随内容变化:浏览器永远不会缓存旧版本);
  • 第 43 行:显示的列表,由输入框和复选框过滤;
  • 第 56 行:[v-bind:src="expression"],缩写为 [:src="expression"],把表达式的值赋给属性 [src]。没有冒号时,[src="logoUrl"] 指的是一个名为“logoUrl”的文件;
  • 第 71 行:当条件为 false 时,[v-show] 会隐藏该元素([display: none])。该元素仍保留在页面上;
  • 第 76–78 行:[v-if]、[v-else-if]、和 [v-else]:这三个元素中,任一时刻页面上 只存在 其中一个。对于经常显示和隐藏的元素,我们选择 [v-show] ,其他情况则使用 [v-if] ;
  • 第 86 行:[v-for] 为每位医生重复该元素;[index] 是它的序号(从 0 开始)。属性 [:key="m.id"] 为每一行赋予一个 标识:当列表变化时,[Vue.js] 就知道要添加、删除或移动哪些行,而不是从头重建全部内容。key 必须唯一且稳定:我们使用对象的标识符,绝不使用它的序号;
  • 第 86 行:[:class] 配合 对象:如果条件为 true,则添加类 [text-muted] ;
  • 第 92 行:[:class] 配合 数组:多个类,其中包括一个计算得出的类;
  • 第 101 行:[:style] 配合由计算得出的属性构成的对象 [CSS] (使用 [camelCase])。

Image

当过滤条件没有返回任何结果时,会显示 [v-else-if] 段落:

Image

2.4. 示例 04:事件

<!--
  =========================================================================
  04-events/src/App.vue - reacting to the user's actions
  -------------------------------------------------------------------------
  v-on:event="handler" (short form @event="handler"):
    - @click="f"          calls f(nativeEvent);
    - @click="f(3, $event)" calls f with arguments; $event is
                          the native event of the browser;
    - modifiers: @submit.prevent (prevents the classic submission of the
      form), @keyup.enter (only the Enter key), @click.stop...
  =========================================================================
-->
<script setup lang="ts">
import { ref } from 'vue';

interface Task {
  id: number;
  label: string;
  done: boolean;
}

const tasks = ref<Task[]>([
  { id: 1, label: 'Install Node.js', done: true },
  { id: 2, label: 'Read the chapter on events', done: false },
]);
const newTask = ref('');
const log = ref<string[]>([]);
let nextId = 3;

function trace(message: string): void {
  log.value.unshift(`${new Date().toLocaleTimeString()} ${message}`);
}

// 由 @submit.prevent 调用:浏览器不会把表单发送给
// 服务器(不重新加载页面),而是由我们的代码来处理
function add(): void {
  const label = newTask.value.trim();
  if (label === '') {
    return;
  }
  tasks.value.push({ id: nextId++, label, done: false });
  trace(`added "${label}"`);
  newTask.value = '';
}

function remove(task: Task): void {
  tasks.value = tasks.value.filter((t) => t.id !== task.id);
  trace(`removed "${task.label}"`);
}

// $event:原生事件(这里是 MouseEvent),带有它的坐标
function position(event: MouseEvent): void {
  trace(`click at (${event.offsetX}, ${event.offsetY})`);
}
</script>

<template>
  <div class="container py-4">
    <h1 class="h3 mb-3">Example 04 - events</h1>

    <!-- @submit.prevent:在字段中按 Enter,或点击按钮 -->
    <form class="d-flex gap-2 mb-3" @submit.prevent="add">
      <input v-model="newTask" class="form-control" placeholder="new task" @keyup.esc="newTask = ''">
      <button type="submit" class="btn btn-primary">Add</button>
    </form>

    <ul class="list-group mb-3">
      <li v-for="t in tasks" :key="t.id" class="list-group-item d-flex align-items-center gap-2">
        <input v-model="t.done" type="checkbox" class="form-check-input" @change="trace(`“${t.label}”: ${t.done ? 'done' : 'to do'}`)">
        <span :class="{ 'text-decoration-line-through text-muted': t.done }" class="flex-grow-1">{{ t.label }}</span>
        <!-- 带参数的处理函数:这一行对应的任务 -->
        <button class="btn btn-sm btn-outline-danger" @click="remove(t)">Delete</button>
      </li>
    </ul>

    <div class="area p-3 mb-3 rounded" @click="position($event)">Click in this area</div>

    <h2 class="h6">Log</h2>
    <ul class="small">
      <li v-for="(line, i) in log" :key="i">{{ line }}</li>
    </ul>
  </div>
</template>

<style scoped>
.area {
  background: #e9f2ff;
  height: 80px;
  cursor: crosshair;
}
</style>
  • 第 62 行:[v-on:submit],缩写为 [@submit],监听表单的 [submit] 事件(在字段中按 Enter 或点击按钮)。修饰符 [.prevent] 会调用 [event.preventDefault()]:浏览器不会把表单发送到服务器,也不会重新加载页面;执行的是函数 [add];
  • 第 63 行:按键修饰符:只有按下 Esc 才会触发处理函数。这是写在模板中的一条简单指令;
  • 第 69 行:处理函数可以是带参数的函数调用;
  • 第 72 行:每个按钮把它自己的任务传给 [remove];
  • 第 76 行:[$event] 指的是浏览器的原生事件——此处是 [MouseEvent]——以及点击坐标;
  • 第 36–43 行:添加任务就是向响应式数组中添加一个对象;清空输入框就是清空与它关联的数据;
  • 第 46–47 行:数组被替换为一个经过过滤的副本。[Vue.js] 既能跟踪“原地”修改([push]、[splice]),也能跟踪整体替换。

Image

2.5. 示例 05:表单字段

与 [NestJS] 课程中示例 18 的表单相同,但这里一切都在浏览器中完成:

<!--
  =========================================================================
  05-forms/src/App.vue - all the field types, linked by v-model
  -------------------------------------------------------------------------
  v-model="data" links a form field to a reactive piece of data, in
  BOTH directions: typing in the field modifies the data, and modifying the
  data (by code) modifies the field. The data received depends on the field:
    - text input, textarea              -> string
    - input + .number                   -> number
    - single checkbox                   -> boolean
    - checkboxes on the same array      -> string[] (the checked values)
    - radio buttons                     -> the value of the chosen button
    - select / select multiple          -> the value / an array of values
    - input type="date"                 -> string "yyyy-MM-dd"
  Modifiers: .trim (spaces removed), .number, .lazy (update when
  leaving the field rather than on each key).
  Same form as example 18 of the NestJS course; but here, no
  server: everything happens in the browser.
  =========================================================================
-->
<script setup lang="ts">
import { reactive, ref } from 'vue';

const titles = ['Mr', 'Mme', 'Melle'];
const possibleHobbies = ['sport', 'music', 'reading', 'cinema'];
const countries = [
  { code: 'fr', name: 'France' },
  { code: 'be', name: 'Belgium' },
  { code: 'ch', name: 'Switzerland' },
];

// 表单的所有值,放在一个响应式对象中
const form = reactive({
  title: 'Mme',
  name: '',
  age: 30,
  presentation: '',
  newsletter: false,
  hobbies: ['reading'] as string[],
  country: 'fr',
  languages: [] as string[],
  birthDate: '',
});

const sent = ref<string | null>(null);

function send(): void {
  // JSON.stringify:我们将发送给服务器的内容(见示例 18)
  sent.value = JSON.stringify(form, null, 2);
}
</script>

<template>
  <div class="container py-4">
    <h1 class="h3 mb-3">Example 05 - the fields of a form</h1>
    <div class="row g-4">
      <form class="col-md-7" @submit.prevent="send">
        <div class="mb-3">
          <span class="form-label d-block">Title</span>
          <!-- 单选按钮:相同的 v-model,每个按钮一个值 -->
          <div v-for="t in titles" :key="t" class="form-check form-check-inline">
            <input :id="'title-' + t" v-model="form.title" type="radio" :value="t" class="form-check-input">
            <label :for="'title-' + t" class="form-check-label">{{ t }}</label>
          </div>
        </div>
        <div class="row g-3 mb-3">
          <div class="col-8">
            <label class="form-label" for="name">Name</label>
            <!-- .trim:" martin " 变成 "martin" -->
            <input id="name" v-model.trim="form.name" class="form-control">
          </div>
          <div class="col-4">
            <label class="form-label" for="age">Age</label>
            <!-- .number:数据接收的是数字,而不是字符串 "30" -->
            <input id="age" v-model.number="form.age" type="number" class="form-control">
          </div>
        </div>
        <div class="mb-3">
          <label class="form-label" for="presentation">About you</label>
          <textarea id="presentation" v-model="form.presentation" rows="2" class="form-control"></textarea>
        </div>
        <div class="mb-3 form-check">
          <!-- 单个复选框:true / false -->
          <input id="newsletter" v-model="form.newsletter" type="checkbox" class="form-check-input">
          <label for="newsletter" class="form-check-label">Receive the newsletter</label>
        </div>
        <div class="mb-3">
          <span class="form-label d-block">Hobbies</span>
          <!-- 同一个数组上的多个复选框:被选中的值 -->
          <div v-for="h in possibleHobbies" :key="h" class="form-check form-check-inline">
            <input :id="'hobby-' + h" v-model="form.hobbies" type="checkbox" :value="h" class="form-check-input">
            <label :for="'hobby-' + h" class="form-check-label">{{ h }}</label>
          </div>
        </div>
        <div class="row g-3 mb-3">
          <div class="col-6">
            <label class="form-label" for="country">Country</label>
            <select id="country" v-model="form.country" class="form-select">
              <!-- :value:传递的值(代码),显示的文本是名称 -->
              <option v-for="c in countries" :key="c.code" :value="c.code">{{ c.name }}</option>
            </select>
          </div>
          <div class="col-6">
            <label class="form-label" for="languages">Spoken languages</label>
            <select id="languages" v-model="form.languages" multiple class="form-select" size="3">
              <option value="fr">French</option>
              <option value="en">English</option>
              <option value="es">Spanish</option>
            </select>
          </div>
        </div>
        <div class="mb-3">
          <label class="form-label" for="birthDate">Date of birth</label>
          <input id="birthDate" v-model="form.birthDate" type="date" class="form-control w-auto">
        </div>
        <button type="submit" class="btn btn-primary">Send</button>
      </form>

      <div class="col-md-5">
        <h2 class="h6">The model, live</h2>
        <!-- {{ object }} 以 JSON 格式显示对象 -->
        <pre class="bg-light p-2 rounded small">{{ form }}</pre>
        <template v-if="sent">
          <h2 class="h6">Last submission</h2>
          <pre class="bg-success-subtle p-2 rounded small">{{ sent }}</pre>
        </template>
      </div>
    </div>
  </div>
</template>
  • 第 33–43 行:所有表单值,放在一个响应式对象中。注解 [as string[]] 向 [TypeScript] 指明数组的类型,因为无法从 [[]] 推断出该类型;
  • 第 62 行:单选按钮共用同一个 [v-model];数据接收被选中按钮的值([:value]);
  • 第 70 行:修饰符 [.trim] 会去掉首尾空格;
  • 第 75 行:[.number] 把输入转换为数字。没有它,数据会被设置为字符串 ["30"]:HTML 字段只包含文本;
  • 第 84 行:单个复选框返回布尔值;
  • 第 91 行:多个复选框关联到同一个数组:该数组包含被选中复选框的值;
  • 第 100 行:对于下拉列表,[:value] 是传递的值(国家代码);选项的文本只是它的标签;
  • 第 105 行:多选列表得到的结果是一个数组;
  • 第 114 行:日期字段返回字符串 ["yyyy-MM-dd"],与浏览器如何显示它无关;
  • 第 122 行:[{{ object }}] 以 JSON 格式显示对象:你可以看到模板随每次按键而变化;
  • 第 49 行:[JSON.stringify(form, null, 2)] 为对象生成缩进 2 个空格的 JSON 文本。这就是将要发送给服务器的内容(见示例 18)。

Image

2.6. 示例 06:表单验证

我们将使用 [RdvMedecins] 服务器上“创建患者账户”表单的规则,并在用户输入时于浏览器中验证它们:

<!--
  =========================================================================
  06-validation/src/App.vue - validating a form in the browser
  -------------------------------------------------------------------------
  The errors are COMPUTED values: they are recomputed on each keystroke.
  They are not displayed right away (an empty form covered in red is
  unpleasant): only for a field already left ("touched"), or for
  all the fields after a submission attempt.

  Same rules as the RdvMedecins server ("Create a patient account" form):
  title in the list, first name and last name required (20 characters at most),
  login in lower case, password of at least 6 characters, confirmation.

  WARNING: this validation is only a COMFORT for the user (an
  immediate answer, without a round trip to the server). It protects
  nothing: anyone can send the server a request built by
  hand (curl...). The server therefore ALWAYS revalidates everything (see example 20).
  =========================================================================
-->
<script setup lang="ts">
import { computed, reactive, ref } from 'vue';

const TITLES = ['Mr', 'Mme', 'Melle'];
const LOGIN_FORMAT = /^[a-z0-9._-]{1,30}$/;
const PASSWORD_MIN = 6;

type Field = 'title' | 'firstName' | 'lastName' | 'login' | 'password' | 'confirmation';

const input = reactive<Record<Field, string>>({
  title: 'Mr',
  firstName: '',
  lastName: '',
  login: '',
  password: '',
  confirmation: '',
});

// 用户已经离开的字段(blur 事件)
const touched = reactive(new Set<Field>());
const submitAttempted = ref(false);
const success = ref(false);

// 每个字段的错误('' = 没有错误),随每次按键重新计算
const errors = computed<Record<Field, string>>(() => ({
  title: TITLES.includes(input.title) ? '' : 'Choose a title from the list.',
  firstName: required(input.firstName, 'The first name') || maximum(input.firstName, 'The first name', 20),
  lastName: required(input.lastName, 'The last name') || maximum(input.lastName, 'The last name', 20),
  login:
    required(input.login, 'The login') ||
    (LOGIN_FORMAT.test(input.login.trim())
      ? ''
      : 'Unaccented lower-case letters, digits, dot, hyphen, underscore.'),
  password:
    required(input.password, 'The password') ||
    (input.password.length < PASSWORD_MIN ? `At least ${PASSWORD_MIN} characters.` : ''),
  confirmation: input.confirmation === input.password ? '' : 'The confirmation does not match the password.',
}));

const formValid = computed(() => Object.values(errors.value).every((e) => e === ''));

function required(value: string, name: string): string {
  return value.trim() === '' ? `${name} is required.` : '';
}
function maximum(value: string, name: string, max: number): string {
  return value.trim().length > max ? `${name} must not exceed ${max} characters.` : '';
}

// 字段要显示的错误:只有在它被触碰过,或者在
// 尝试提交之后才显示
function visibleError(field: Field): string {
  return touched.has(field) || submitAttempted.value ? errors.value[field] : '';
}

function send(): void {
  submitAttempted.value = true;
  success.value = formValid.value;
}
</script>

<template>
  <div class="container py-4" style="max-width: 640px">
    <h1 class="h3 mb-3">Example 06 - form validation</h1>
    <!-- novalidate: the browser's own validation is disabled, to
         display OUR messages, in OUR style -->
    <form class="card p-4" novalidate @submit.prevent="send">
      <div class="mb-3">
        <label class="form-label" for="title">Title</label>
        <select id="title" v-model="input.title" class="form-select" :class="{ 'is-invalid': visibleError('title') }">
          <option v-for="t in TITLES" :key="t">{{ t }}</option>
        </select>
      </div>
      <div class="row g-3 mb-3">
        <div class="col-sm-6">
          <label class="form-label" for="firstName">First name</label>
          <!-- @blur: the user leaves the field, which becomes "touched";
               the Bootstrap class is-invalid frames it in red and makes
               the following .invalid-feedback appear -->
          <input id="firstName" v-model="input.firstName" class="form-control"
                 :class="{ 'is-invalid': visibleError('firstName') }" @blur="touched.add('firstName')">
          <div class="invalid-feedback">{{ visibleError('firstName') }}</div>
        </div>
        <div class="col-sm-6">
          <label class="form-label" for="lastName">Last name</label>
          <input id="lastName" v-model="input.lastName" class="form-control"
                 :class="{ 'is-invalid': visibleError('lastName') }" @blur="touched.add('lastName')">
          <div class="invalid-feedback">{{ visibleError('lastName') }}</div>
        </div>
      </div>
      <div class="mb-3">
        <label class="form-label" for="login">Login</label>
        <input id="login" v-model="input.login" class="form-control" autocomplete="username"
               :class="{ 'is-invalid': visibleError('login'), 'is-valid': touched.has('login') && !errors.login }"
               @blur="touched.add('login')">
        <div class="invalid-feedback">{{ visibleError('login') }}</div>
      </div>
      <div class="row g-3 mb-4">
        <div class="col-sm-6">
          <label class="form-label" for="password">Password</label>
          <input id="password" v-model="input.password" type="password" class="form-control" autocomplete="new-password"
                 :class="{ 'is-invalid': visibleError('password') }" @blur="touched.add('password')">
          <div class="invalid-feedback">{{ visibleError('password') }}</div>
        </div>
        <div class="col-sm-6">
          <label class="form-label" for="confirmation">Confirmation</label>
          <input id="confirmation" v-model="input.confirmation" type="password" class="form-control" autocomplete="new-password"
                 :class="{ 'is-invalid': visibleError('confirmation') }" @blur="touched.add('confirmation')">
          <div class="invalid-feedback">{{ visibleError('confirmation') }}</div>
        </div>
      </div>
      <button type="submit" class="btn btn-primary">Create the account</button>
      <div v-if="submitAttempted && !formValid" class="alert alert-danger mt-3 mb-0">The form contains errors.</div>
      <div v-if="success" class="alert alert-success mt-3 mb-0">Valid form: it could be sent to the server.</div>
    </form>
  </div>
</template>
  • 第 27 行:字段名的类型。[Record<Field, string>] 是一个恰好具有这些属性的对象:字段名中的拼写错误会在编译时被发现;
  • 第 39 行:用户已经离开的字段。一个响应式的 [Set]:[touched.add(...)] 会更新页面;
  • 第 44–57 行:各字段的错误,随每次按键重新计算。空字符串表示“没有错误”;[a || b] 在 [a] 为空时返回 [b] :这样我们就能对一个字段的各项检查进行链式组合,第一个未通过的检查会触发其消息;
  • 第 59 行:如果没有错误则为 true;
  • 第 70–72 行:只有当字段被“触碰过”,或者在尝试提交之后,才会显示该字段的错误。在用户还没开始填写时就把空表单标红,会让人很不舒服;
  • 第 85 行:[novalidate] 禁用浏览器自带的检查(属性 [required]……),这样只会以我们自己的样式显示我们自己的消息;
  • 第 99 行:[blur] 事件:用户离开该字段;
  • 第 99 行:[Bootstrap] 类 [is-invalid] 会用红色框出该字段,并显示紧随其后的 [<div class="invalid-feedback">] ;
  • 第 112 行:[is-valid]则相反,会用绿色框出它。

点击“创建账户”后,表单被清空:

Image

然后,在表单填写正确之后:

Image

一个重要提示:这种验证只是一种 便利手段。它能立即响应,无需往返服务器,但不提供任何保护:任何人都可以绕过我们的页面,手工构造请求发送给服务器(例如使用 [curl])。因此服务器必须对收到的内容重新验证。在示例 20 以及后面的案例研究中,我们会看到另一种做法:由服务器负责验证并显示消息。