跪拜 Guibai
← Back to the summary

Vue v-model's Three Fake Syncs That Leave Captchas Stuck on 'Passed'

Click the form's "Reset" button: the input empties, the dropdown returns to its placeholder, but the slider captcha stays green with "Verified", and can't be dragged; the click captcha also stays in the passed state.

The parent component clearly set v-model back to false. This isn't a captcha problem, it's the three most common kinds of "fake sync" in Vue controlled components.

This issue doesn't show up in a demo: the default value is false, so everything works; it only comes out after you pass once and then click reset. Below, we go through "reproduction → three patterns → correct template → testing and scanning".

Minimal reproduction

<SliderCaptcha v-model="captchaPassed" />
<button @click="captchaPassed = false">Reset</button>

After clicking reset, captchaPassed is already false, but the component still shows "Verified". Same for the click captcha. Running the same operations with two builds we get:

Operation 0.2.28 component state 0.2.29 component state
Initial modelValue=true slider false / click false true / true
Change to false (reset) false / false false / false
Change back to true still false / false true / true

In 0.2.28, the parent's value never entered the component at all — two of the three states were wrong. Two components, same operations, identical results: this isn't a one-off bug in a component, it's a pattern problem.

The version that's easier to hit in business code

Real forms rarely have just a single captcha:

<Form ref="formRef" :model="form">
  <FormItem label="Phone" prop="phone"><Input v-model="form.phone" /></FormItem>
  <FormItem label="Captcha" prop="captcha">
    <SliderCaptcha v-model="form.captchaPassed" />
  </FormItem>
  <button @click="formRef.resetFields()">Reset</button>
</Form>

resetFields() restores each field in form to its initial value, and captchaPassed goes from true back to false. The input and dropdown update. Only the captcha doesn't move — because the captcha component doesn't listen to that field. Business developers usually suspect the form library first and the component last, so this bug can live a long time.

Fake sync #1: only emits, doesn't declare the prop

ClickCaptcha's meta description says "v-model sets true", and the events include update:modelValue:

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  success: [];
  fail: [];
}>();

const passed = ref(false); // never reads props.modelValue

But the props don't have modelValue at all. v-model expands into "a prop + an event":

<ClickCaptcha :model-value="passed" @update:model-value="passed = $event" />

If the component doesn't declare the prop, Vue treats it as a plain attribute and passes it through. passed always starts at false; later writes of true or false from the parent never arrive. It finished the "send out" half but not the "receive in" half.

This pattern is the easiest to document as "supports v-model", because the event is indeed emitted; but the type definition has no prop, and neither the IDE nor tests complain.

The fix is to add the prop and initialization:

interface ClickCaptchaProps {
  modelValue?: boolean;
}
const props = withDefaults(defineProps<ClickCaptchaProps>(), { modelValue: false });
const passed = ref(props.modelValue);

Fake sync #2: snapshot initialization + wipe on mount

SliderCaptcha looks like it reads the prop:

const passed = ref(props.modelValue);

But it calls onMounted(reset) when it mounts, and the first line of reset is passed.value = false. So an external true gets wiped back to false.

Worse: there's no watch. If the parent later changes the value to false, the component doesn't know; if it changes to true, the component doesn't know either. The so-called "controlled" state exists only at the instant of initialization, and afterwards it's one-way.

This snapshot-controlled pattern is common in components where "the default value is the final value": as long as the parent never resets, it never shows a problem.

The fix is to separate "reset visual" from "reset state":

function resetVisual() {
  pieceX.value = 0;
  gapX.value = randomGap();
  bgUrl.value = makeBackground();
}

onMounted(() => {
  resetVisual();               // only initialize visuals
  if (passed.value) pieceX.value = gapX.value; // align when external true
});

watch(() => props.modelValue, (value) => {
  if (value === passed.value) return;
  passed.value = value;
  if (value) pieceX.value = gapX.value;
  else resetVisual();
});

There's a detail here: don't call a reset() that emits inside the watch. reset() will emit "update:modelValue", false, the parent writes it back, which causes extra events at best and an infinite loop at worst. Use a resetVisual() that emits nothing.

Fake sync #3: watch only acknowledges truthy

The third is the most sneaky, and the code usually looks like this:

watch(() => props.modelValue, (value) => {
  if (value) inner.value = value;
});

It handles true, but treats false, 0, and '' as "no new value". Form reset happens to set the value to false, so it never takes effect. This pattern has appeared in quite a few components — our own Tabs was like this before, and only in 0.2.28 did we change it to "if the value doesn't match, fall back to the first available item".

The judgement standard is simple: every legal value of a controlled field must be writable, including falsy values.

Why v-model "lies"

v-model compiles in the template into a pair of bindings:

<SliderCaptcha :model-value="passed" @update:model-value="passed = $event" />

Props only go down, events only go up — that's Vue's one-way data flow. For a component to be "controlled", both sides must be connected: read the prop to decide the current state, then emit to inform the parent on user action. A component that only emits is actually an "uncontrolled component + notification" — the parent hears the change but can't move it.

There's a simple experiment to tell if a component is truly controlled: in the parent, change the value to another legal value and see if the component changes. If it changes, it's controlled; if it only syncs when the user clicks, it's "half-controlled".

The correct controlled pattern

Combining the three above into one template:

const props = withDefaults(defineProps<{ modelValue?: boolean }>(), {
  modelValue: false,
});
const emit = defineEmits<{ "update:modelValue": [v: boolean] }>();

const inner = ref(props.modelValue);

watch(() => props.modelValue, (value) => {
  if (value === inner.value) return; // avoid repeated reset
  inner.value = value;
  if (!value) resetVisual();         // external reset -> only reset visuals
});

function reset() {                    // internal active reset -> notify parent
  inner.value = false;
  resetVisual();
  emit("update:modelValue", false);
}

Three constraints:

  1. The prop must actually be declared; emitting alone doesn't make it controlled.
  2. The watch must cover all legal values; don't check only truthy.
  3. External sync and internal notification must be separate: no emit in the watch, emit only in reset.

Edge cases: falsy values, references, async

Why the original unit test didn't catch it

SliderCaptcha already had an existing test case "when external modelValue=true, show passed state", and it was always green:

const wrapper = mount(SliderCaptcha, { props: { modelValue: true } });
expect(wrapper.classes()).toContain("rn-slider-captcha--passed");

onMounted(reset) changed the state to false, but that reactive update only entered the queue; the DOM still had the mount-time "passed" state. The assertion ran before nextTick and read the stale DOM — the test passed, but the component was broken.

Change the test to wait one frame and it immediately turns red:

await nextTick();
expect(wrapper.classes()).toContain("rn-slider-captcha--passed");

After the fix, three test cases cover initial value, external reset, and re-drag after reset:

it("recovers to not-passed after parent changes back to false", async () => {
  const wrapper = mount(SliderCaptcha, { props: { modelValue: true } });
  await nextTick();
  expect(wrapper.classes()).toContain("rn-slider-captcha--passed");

  await wrapper.setProps({ modelValue: false });
  await nextTick();
  expect(wrapper.classes()).not.toContain("rn-slider-captcha--passed");

  await wrapper.find(".rn-slider-captcha__track")
    .trigger("pointerdown", { pointerId: 1, clientX: 10 });
  expect(wrapper.find(".rn-slider-captcha__track").classes())
    .toContain("rn-slider-captcha__track--dragging");
});

Test matrix: emitting alone isn't enough

A controlled component should cover at least four kinds of cases:

Case Assertion
Initial value External true/false/0/'' makes the component render in that state on first mount
External write After setProps changes the value, component state follows (with await nextTick())
Internal action After click/drag, emits the correct value and updates its own state
Reset After external change back to false, visual, progress, and interactivity all restore

The original SliderCaptcha had only one case of the first kind, and the assertion ran before nextTick; the second and fourth were entirely missing. After filling them in, these three problems were locked down for the first time. The common prerequisite for all four is: await nextTick() before asserting, or you'll read stale DOM.

A reproducible scan script

This kind of problem can be statically scanned. Save the following as scan-controlled.mjs and pass it a component directory:

import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

const dir = process.argv[2] ?? "src/components";
for (const name of readdirSync(dir)) {
  const file = join(dir, name, name + ".vue");
  let src = "";
  try { src = readFileSync(file, "utf8"); } catch { continue; }

  const emitsMV = src.includes('"update:modelValue"');
  const hasProp = /modelValue\??\s*:/.test(src);
  const snap = /ref(?:<[^>]*>)?\(props\.modelValue\)/.test(src);
  const watches = /watch\(\s*\(\)\s*=>\s*props\.modelValue/.test(src);
  const truthyOnly = /watch\(\s*\(\)\s*=>\s*props\.modelValue[\s\S]{0,120}?if\s*\(\s*(val|value|v)\s*\)/.test(src);

  if (emitsMV && !hasProp) console.log(name, "emits update:modelValue but has no modelValue prop");
  else if (snap && !watches) console.log(name, "reads initial modelValue but has no watch");
  else if (truthyOnly) console.log(name, "watch only handles truthy, false/0/'' get swallowed");
}

It scanned our 97 components and found 5 candidates: 2 real bugs (ClickCaptcha missing prop, SliderCaptcha missing watch) and 3 false positives (Dialog/Drawer/MessageBox use if/else in the watch, so falsy values have a branch). The scan only narrows the candidates to 5; whether each is real still needs manual confirmation.

Hook it into the CI lint step; as soon as a new component "emits without declaring prop" it gets exposed before merge. Whitelist false positives with comments; don't delete the rule just to get zero warnings. The script only does regex matching, not AST parsing; controlled fields with different names (like checked, visible) need different rules.

What happens with defineModel

Vue 3.4+ lets you write:

const model = defineModel<boolean>({ default: false });

watch(model, (value) => {
  if (!value) resetVisual();
});

That drops one prop declaration and a pair of emits, and v-model works automatically. But it only solves the first kind of fake sync; the other two still have to be written by hand: the mount-time value must not be wiped, and the watch must not check only truthy. defineModel is syntactic sugar, not insurance for controlled semantics.

Also, assigning inside a watch on defineModel triggers update:modelValue, which is no safer than handwritten emits; the rule "external sync doesn't go through emit" still holds.

Approach What you write less What you still write yourself
props + emit nothing prop declaration, watch, separated emit
defineModel prop and emit watch all legal values, external sync does not emit
non-controlled + key no sync needed parent changes key to force rebuild, all state lost

The third approach is actually usable for "reset": <SliderCaptcha :key="resetKey" />, increment resetKey on reset, and the whole component rebuilds. The cost is that during the rebuild the canvas regenerates and animation restarts; for a lightweight captcha that's fine, but complex form controls will flash. defineModel reduces boilerplate but doesn't change semantics — the watch lines that need to be written are still there.

Results

Version 0.2.29 released:

0.2.28: ref is true, but both components' passed states are false

0.2.28 reset: ref becomes false, component was already false, so no difference shows

0.2.28 set true again: ref is true, component still false — external value never came in

0.2.29 initial true: both components show passed

0.2.29 reset: both components return to not-passed, click progress 1/3

0.2.29 set true again: both components sync back to passed

Dragging after reset: can enter dragging state properly

Online example (0.2.29): form reset demo, status shown next to button

After reset: text changes to "not passed: reset should return to clickable state"

Props table now includes modelValue: default false, clears progress when parent resets to false

Conclusion

v-model isn't a single event; it's a pair of contracts: the prop brings the value in, the emit carries the value out. Doing only half is fake control. Most bugs in controlled components aren't wrong logic — they're contracts written only halfway.

Three self-checks, in order; if the earlier check fails, the later ones don't matter:

  1. If the component contains update:modelValue, there must be a prop of the same name; a v-model without a prop is just "can receive a notification", not "can accept control".
  2. As soon as a component copies a prop into a local ref, it must have a watch, and that watch must cover false / 0 / ''.
  3. External sync and internal notification must be separate: in the watch only change local state, emit only on user action.

The third is the easiest to trip over this time: reusing reset() inside the watch looks like the least work, but it sends the parent's value back out; splitting out a resetVisual() that emits nothing closes the loop.

After writing a component, run a 30-second experiment: put two buttons in the parent, one to set the value to true, one to set it to false, and click each. If the component doesn't follow, it's not controlled.


Component Anatomy · Series Index

Online example: https://ui.ruanno.top/components/click-captcha Source code: https://gitee.com/ruanno-top/ruanno-ui

Comments

Top 1 of 3 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

The third fake sync is the easiest to fall for. When writing if(value) in a watch, you think you're syncing only when there's a new value, but false, 0, and empty strings all get treated as no new value — and form resets just happen to set the value to false. Also the unit test part resonates a lot: asserting before nextTick reads the old DOM and still sees green, and that fake green is scarier than red. I'd like to ask: after you hook the scanning script into CI, the three false positives Dialog, Drawer, MessageBox — are they suppressed with a comment whitelist? If new components later have similar if/else branches, will you have to keep adding whitelist entries one by one?

ruanno_top

It's not actually hooked into CI yet — the script in the article is a template for everyone to adapt. The three false positives came from the regex only seeing if (value) without the else that follows; temporarily we whitelist by 'component name + rule name'. A new component hitting the same rule will first raise an alert and then get manual confirmation. Next step is to switch to @vue/compiler-sfc to parse the watch callback, which can distinguish between 'only handling truthy' and 'full if/else coverage', so there's no need to keep adding whitelist entries.

组合搭配函数  → ruanno_top

I accept that it's not actually hooked into CI yet — a template script and a CI gate are two different things, and getting it running before tightening is right. But I don't think the 'component + rule' whitelist can hold up for long — with more new components, the whitelist only grows longer and eventually no one dares to touch it. Switching to @vue/compiler-sfc to parse the watch callback and distinguishing 'truthy-only' from 'full if/else coverage' is the real solution. After that, the whitelist should only keep historical legacy and never admit new entries. Are you planning to implement the parsing first, or set up the whitelist's expiry mechanism first?