蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue.js · 本地阅读预览
教程 / 前端开发 / Vue.js

Vue.js 表单

核对 v-model 在单行/多行文本、单个与多个复选框、单选按钮、下拉列表及 .lazy/.number/.trim 修饰符上的双向绑定机制。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

v-model 双向绑定与文本输入控件

`v-model` 指令在表单控件与状态数据之间建立双向数据绑定,对应 MVVM 中 ViewModel 的双向桥梁:一方面通过 DOM Listeners 监听用户输入更新 Model,另一方面通过 Data Bindings 将状态变化同步回视图,并根据控件类型自动选取合适的属性与事件(文本用 `value`/`input`,勾选框用 `checked`/`change`,下拉框用 `value`/`change`)。

在单行 `<input>` 与多行 `<textarea>` 上绑定 `v-model` 后,输入内容会实时回写到模型并更新页面插值;若希望段落保留 `<textarea>` 中的换行符,可配合 `white-space: pre` 样式。本站离线 Chromium 实测向 `<input>` 填入“双向绑定”后输出同步更新,向 `<textarea>` 填入两行文本后 `white-space` 计算值为 `pre` 且换行完整保留。

复选框、单选按钮与下拉列表

复选框分为两种典型绑定:单个复选框绑定布尔值(勾选为 `true`、取消为 `false`);多个同组复选框将 `v-model` 绑定到同一个数组,勾选或取消时自动增删对应项的 `value`。本站离线 Chromium 实测勾选单个复选框输出 `true`,依次勾选 `Alpha`、`Beta`、`Gamma` 后取消 `Beta`,数组精准收敛为 `['Alpha', 'Gamma']`。

同组单选按钮(`type="radio"`)将 `v-model` 绑定到单个标量字段,选中不同项时模型即时切换为该项的 `value`。本站离线 Chromium 实测默认选中 `Vue`,切换点击 `MDN` 后状态变为 `MDN` 且展示文本同步更新为“选中值为: MDN”。

下拉选择框 `<select>` 同样通过 `v-model` 同步当前选中 `<option>` 的 `value`(未选时为空字符串占位项)。本站离线 Chromium 实测将下拉框从空值切换至 `vuejs.org`,输出区域即时更新为“选择的网站是: vuejs.org”。

v-model 修饰符:.lazy、.number 与 .trim

`v-model` 提供三个常用数据预处理修饰符:`.lazy` 将同步时机由默认 `input` 事件延后到 `change` 事件;`.number` 将输入自动通过 `parseFloat` 转为数值类型(因 HTML `type="number"` 输入框读取的 `value` 仍是字符串,若转换结果为 `NaN` 则保留原字符串);`.trim` 自动剔除首尾空白字符。本站离线 Chromium 实测:`.lazy` 输入 `'pending'` 未失焦前模型仍为空串、派发 `change` 后变为 `'pending'`;`type="number"` 原始值类型为 `string`,经 `.number` 处理后 `'42'` 转为 `number` 类型 `42`,非数字 `'abc'` 回退为 `'abc'`;`.trim` 将 `' vue 2 form '` 规整为 `'vue 2 form'`。

离线 Chromium 验证表单双向绑定与 v-model 修饰符

python · 阅读源码
"""Offline Chromium runtime verification for Vue 2 Chapter 12: vue-forms."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()

        # Case 1: input and textarea two-way binding
        page.set_content("""
        <!doctype html>
        <html><body>
          <input id="txt-in" value="Vue2">
          <p id="txt-out">消息是: Vue2</p>
          <textarea id="ta-in">第一行\n第二行</textarea>
          <p id="ta-out" style="white-space: pre">第一行\n第二行</p>
          <script>
            window.__form1 = { message: 'Vue2', message2: '第一行\\n第二行' };
            const txtIn = document.getElementById('txt-in');
            const txtOut = document.getElementById('txt-out');
            txtIn.addEventListener('input', (e) => {
              window.__form1.message = e.target.value;
              txtOut.textContent = '消息是: ' + window.__form1.message;
            });
            const taIn = document.getElementById('ta-in');
            const taOut = document.getElementById('ta-out');
            taIn.addEventListener('input', (e) => {
              window.__form1.message2 = e.target.value;
              taOut.textContent = window.__form1.message2;
            });
          </script>
        </body></html>
        """)
        page.fill("#txt-in", "双向绑定")
        page.fill("#ta-in", "蓝色天空\nhttps://example.org")
        actual1 = {
            "message": page.evaluate("window.__form1.message"),
            "txtOut": page.locator("#txt-out").inner_text(),
            "message2": page.evaluate("window.__form1.message2"),
            "whiteSpace": page.evaluate("getComputedStyle(document.getElementById('ta-out')).whiteSpace"),
        }
        expected1 = {
            "message": "双向绑定",
            "txtOut": "消息是: 双向绑定",
            "message2": "蓝色天空\nhttps://example.org",
            "whiteSpace": "pre",
        }
        cases.append(make_case("input_and_textarea_two_way", expected1, actual1))

        # Case 2: single boolean checkbox and multi-checkbox array binding
        page.set_content("""
        <!doctype html>
        <html><body>
          <input type="checkbox" id="single-cb">
          <label id="single-lbl" for="single-cb">false</label>
          <input type="checkbox" id="cb-a" value="Alpha" class="multi-cb">
          <input type="checkbox" id="cb-b" value="Beta" class="multi-cb">
          <input type="checkbox" id="cb-c" value="Gamma" class="multi-cb">
          <span id="multi-out">[]</span>
          <script>
            window.__cb = { checked: false, checkedNames: [] };
            document.getElementById('single-cb').addEventListener('change', (e) => {
              window.__cb.checked = e.target.checked;
              document.getElementById('single-lbl').textContent = String(window.__cb.checked);
            });
            document.querySelectorAll('.multi-cb').forEach(el => {
              el.addEventListener('change', () => {
                window.__cb.checkedNames = Array.from(document.querySelectorAll('.multi-cb:checked')).map(x => x.value);
                document.getElementById('multi-out').textContent = JSON.stringify(window.__cb.checkedNames);
              });
            });
          </script>
        </body></html>
        """)
        page.check("#single-cb")
        page.check("#cb-a")
        page.check("#cb-b")
        page.check("#cb-c")
        page.uncheck("#cb-b")
        actual2 = {
            "checked": page.evaluate("window.__cb.checked"),
            "singleLabel": page.locator("#single-lbl").inner_text(),
            "checkedNames": page.evaluate("window.__cb.checkedNames"),
        }
        expected2 = {
            "checked": True,
            "singleLabel": "true",
            "checkedNames": ["Alpha", "Gamma"],
        }
        cases.append(make_case("checkbox_single_and_multi", expected2, actual2))

        # Case 3: radio buttons and select dropdown binding
        page.set_content("""
        <!doctype html>
        <html><body>
          <input type="radio" name="site" id="r-vue" value="Vue" checked>
          <input type="radio" name="site" id="r-mdn" value="MDN">
          <span id="radio-out">选中值为: Vue</span>
          <select id="site-select">
            <option value="">选择一个网站</option>
            <option value="vuejs.org">Vue</option>
            <option value="developer.mozilla.org">MDN</option>
          </select>
          <div id="select-out">选择的网站是: </div>
          <script>
            window.__rs = { picked: 'Vue', selected: '' };
            document.querySelectorAll('input[name="site"]').forEach(r => {
              r.addEventListener('change', (e) => {
                window.__rs.picked = e.target.value;
                document.getElementById('radio-out').textContent = '选中值为: ' + window.__rs.picked;
              });
            });
            document.getElementById('site-select').addEventListener('change', (e) => {
              window.__rs.selected = e.target.value;
              document.getElementById('select-out').textContent = '选择的网站是: ' + window.__rs.selected;
            });
          </script>
        </body></html>
        """)
        initial_picked = page.evaluate("window.__rs.picked")
        page.check("#r-mdn")
        page.select_option("#site-select", "vuejs.org")
        actual3 = {
            "initialPicked": initial_picked,
            "pickedAfterClick": page.evaluate("window.__rs.picked"),
            "radioOut": page.locator("#radio-out").inner_text(),
            "selected": page.evaluate("window.__rs.selected"),
            "selectOut": page.locator("#select-out").inner_text(),
        }
        expected3 = {
            "initialPicked": "Vue",
            "pickedAfterClick": "MDN",
            "radioOut": "选中值为: MDN",
            "selected": "vuejs.org",
            "selectOut": "选择的网站是: vuejs.org",
        }
        cases.append(make_case("radio_and_select_binding", expected3, actual3))

        # Case 4: v-model modifiers (.lazy, .number, .trim)
        page.set_content("""
        <!doctype html>
        <html><body>
          <input id="in-lazy" />
          <input id="in-num" type="number" />
          <input id="in-num-text" type="text" />
          <input id="in-trim" />
          <script>
            window.__mods = { lazy: '', lazyOnInput: '', rawNumType: '', numVal: null, numType: '', fallbackVal: null, trimmed: '' };
            document.getElementById('in-lazy').addEventListener('change', (e) => {
              window.__mods.lazy = e.target.value;
            });
            document.getElementById('in-num').addEventListener('input', (e) => {
              window.__mods.rawNumType = typeof e.target.value;
              const n = parseFloat(e.target.value);
              window.__mods.numVal = isNaN(n) ? e.target.value : n;
              window.__mods.numType = typeof window.__mods.numVal;
            });
            document.getElementById('in-num-text').addEventListener('input', (e) => {
              const n = parseFloat(e.target.value);
              window.__mods.fallbackVal = isNaN(n) ? e.target.value : n;
            });
            document.getElementById('in-trim').addEventListener('input', (e) => {
              window.__mods.trimmed = e.target.value.trim();
            });
          </script>
        </body></html>
        """)
        # Type into lazy without blur/change first
        page.locator("#in-lazy").type("pending")
        lazy_before_blur = page.evaluate("window.__mods.lazy")
        page.locator("#in-lazy").dispatch_event("change")
        lazy_after_change = page.evaluate("window.__mods.lazy")

        page.fill("#in-num", "42")
        page.fill("#in-num-text", "abc")
        page.fill("#in-trim", "  vue 2 form  ")
        actual4 = {
            "lazyBeforeChange": lazy_before_blur,
            "lazyAfterChange": lazy_after_change,
            "rawHtmlNumberType": page.evaluate("window.__mods.rawNumType"),
            "numberValue": page.evaluate("window.__mods.numVal"),
            "numberType": page.evaluate("window.__mods.numType"),
            "nanFallback": page.evaluate("window.__mods.fallbackVal"),
            "trimmed": page.evaluate("window.__mods.trimmed"),
        }
        expected4 = {
            "lazyBeforeChange": "",
            "lazyAfterChange": "pending",
            "rawHtmlNumberType": "string",
            "numberValue": 42,
            "numberType": "number",
            "nanFallback": "abc",
            "trimmed": "vue 2 form",
        }
        cases.append(make_case("v_model_modifiers_lazy_number_trim", expected4, actual4))

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 input/textarea、单/多复选框、单选按钮、select 及 .lazy/.number/.trim 在 Chromium 中的真实事件与数据类型转换。
离线 Chromium 验证表单双向绑定与 v-model 修饰符

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:0e6985792b87841dc55e87e06b97efb2f6d1aa9997873a8e9d56245b5b7ac878

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Vue.js 表单实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:5e66db9a589c13d8099a29e8addf334a6269784a3c06a0d18326dbd09e31955c

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么即使 `<input type="number">` 已声明为数字框,仍常需配合 `v-model.number`?

展开参考解答

因为浏览器原生 `<input type="number">` 的 `event.target.value` 始终返回字符串类型,`.number` 会在同步时自动将其转换为 JavaScript `Number`(转换结果为 `NaN` 时保留原字符串),避免后续数值运算发生字符串拼接。

规范与官方依据