Skip to content

fix(runtime-core): avoid setting direct ref of useTemplateRef in dev #13449

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

alex-snezhko
Copy link
Contributor

@alex-snezhko alex-snezhko commented Jun 8, 2025

Avoid directly setting the ref value in dev mode whenever a ref object from a useTemplateRef call is used for rendering, updating only the component owner refs object instead (which useTemplateRef is hooked up to correctly update from).

When code like the following:

<script setup>
import { useTemplateRef } from 'vue'
const myRef = useTemplateRef('myRef')
</script>

<template>
  <div ref="myRef">Foo</div>
</template>

is compiled in inline mode the output would contain:

createElementBlock("div", {
  ref_key: "myRef",
  ref: myRef
}, "Foo")

which then attempts to update the myRef object directly, showing a warning: Set operation on key "value" failed: target is readonly.; this change should avoid this warning from showing.

closes #12852

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of template refs to prevent unintended modifications and ensure correct cleanup in development mode.
  • Tests
    • Expanded test coverage for template refs, including scenarios with direct refs, ref keys, dynamic rendering, and multiple elements.
    • Enhanced transition tests to ensure DOM updates are properly awaited during transitions.

Copy link

coderabbitai bot commented Jun 8, 2025

Walkthrough

The changes introduce new test cases for useTemplateRef to verify its behavior with direct refs and ref_key, and update the internal logic for setting and unsetting template refs in the renderer. Conditional guards are added to prevent setting or reading .value on refs in certain development scenarios, addressing specific warning emissions. A minor adjustment is made to a transition test to ensure correct timing.

Changes

File(s) Change Summary
packages/runtime-core/tests/helpers/useTemplateRef.spec.ts Added multiple tests covering direct ref usage with ref_key and dynamic scenarios.
packages/runtime-core/src/rendererTemplateRef.ts Introduced canSetRef helper and added guards to ref assignments and retrievals for dev mode.
packages/vue/tests/e2e/Transition.spec.ts Inserted additional await nextFrame() in a transition test to ensure DOM update timing.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant Renderer
    participant Ref

    Component->>Renderer: Render with useTemplateRef(ref, ref_key)
    Renderer->>Renderer: Check canSetRef(ref)
    alt canSetRef is true
        Renderer->>Ref: Set ref.value = element
    else canSetRef is false
        Renderer-->>Ref: Skip setting ref.value
    end
    Renderer->>Component: Continue rendering
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent "Set operation on key 'value' failed: target is readonly" warning when using useTemplateRef with direct ref and ref_key (#12852)
Ensure no warnings when useTemplateRef argument matches the variable name after rollup packaging (#12852)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation

Suggested labels

ready to merge, :hammer: p3-minor-bug

Poem

A bunny hopped through Vue’s green land,
Guarding refs with gentle hand.
No warnings now disturb the peace,
As tests and helpers bring release.
With every hop, the code’s refined—
Bugs and errors left behind!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdffaf6 and b8e63f7.

📒 Files selected for processing (3)
  • packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts (1 hunks)
  • packages/runtime-core/src/rendererTemplateRef.ts (6 hunks)
  • packages/vue/__tests__/e2e/Transition.spec.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/runtime-core/src/rendererTemplateRef.ts (2)
packages/runtime-core/src/helpers/useTemplateRef.ts (1)
  • knownTemplateRefs (6-6)
packages/runtime-core/src/vnode.ts (1)
  • VNodeNormalizedRefAtom (94-111)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
  • GitHub Check: test / e2e-test
  • GitHub Check: test / unit-test-windows
🔇 Additional comments (11)
packages/vue/__tests__/e2e/Transition.spec.ts (1)

3084-3086: Verify the necessity of the additional frame wait.

The added await nextFrame() introduces an extra frame delay during the enter transition phase. While this may be necessary to ensure proper DOM/style updates before proceeding with transition finish, please confirm that this timing adjustment is required for the test to pass reliably and isn't masking an underlying issue.

packages/runtime-core/src/rendererTemplateRef.ts (5)

2-7: LGTM! Import changes are appropriate.

The additional type imports (VNodeNormalizedRefAtom and VNodeRef) are necessary for the new type assertions and function signatures in this file.


102-104: Good addition of the canSetRef guard function.

This helper function correctly prevents setting .value on refs that are marked as template refs (created by useTemplateRef) during development, which addresses the "target is readonly" warning issue mentioned in the PR objectives.


114-121: Proper cleanup of old refs with appropriate guards.

The changes correctly:

  1. Guard the oldRef.value = null assignment with canSetRef to prevent readonly warnings
  2. Clean up the refs map entry (refs[oldRawRefAtom.k] = null) to avoid stale references

The type assertion comment is helpful for code clarity.


137-155: Correct handling of array refs with fallback to refs map.

The implementation properly handles refs in v-for loops by:

  1. Checking canSetRef(ref) before accessing ref.value
  2. Falling back to refs[rawRef.k] when direct ref access is blocked
  3. Updating both ref.value (when allowed) and refs[rawRef.k] for consistency

This ensures that refs work correctly even when useTemplateRef is used with ref_for.


166-170: Core fix for the useTemplateRef readonly warning.

This change addresses the main issue by:

  1. Only setting ref.value when canSetRef(ref) returns true
  2. Always updating refs[rawRef.k] to ensure useTemplateRef can access the value through the component's refs map

This prevents the "target is readonly" warning while maintaining correct functionality.

packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts (5)

109-123: Good test coverage for basic ref_key usage.

This test verifies the core fix - that using useTemplateRef with a direct ref value and ref_key attribute works without triggering the "target is readonly" warning.


125-146: Comprehensive test for array refs with ref_for.

This test properly verifies that useTemplateRef works with multiple elements when using ref_for, ensuring the array ref functionality remains intact after the fix.


148-190: Excellent test coverage for dynamic rendering scenarios.

This test thoroughly verifies that the ref updates correctly when:

  • Switching between different element types
  • Removing the ref attribute
  • Rendering null

All scenarios work without triggering readonly warnings, confirming the fix handles dynamic cases properly.


192-221: Well-designed test for dynamic ref switching.

This test validates that dynamically switching between different useTemplateRef instances and their corresponding keys works correctly, ensuring the fix handles reactive ref selection scenarios.


223-235: Important negative test case.

This test confirms that without the ref_key attribute, the direct ref value is not updated (remains null). This is the expected behavior and ensures the fix only applies when ref_key is explicitly provided.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented Jun 8, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB (+42 B) 38.4 kB (+12 B) 34.6 kB (+2 B)
vue.global.prod.js 159 kB (+42 B) 58.6 kB (+11 B) 52.1 kB (-37 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.7 kB (+42 B) 18.2 kB (+8 B) 16.7 kB (+7 B)
createApp 54.7 kB (+42 B) 21.3 kB (+11 B) 19.4 kB (-7 B)
createSSRApp 58.9 kB (+42 B) 23 kB (+11 B) 21 kB
defineCustomElement 59.6 kB (+42 B) 22.9 kB (+13 B) 20.9 kB (+4 B)
overall 68.8 kB (+42 B) 26.5 kB (+9 B) 24.1 kB (+24 B)

Copy link

pkg-pr-new bot commented Jun 8, 2025

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@13449

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@13449

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@13449

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@13449

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@13449

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@13449

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@13449

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@13449

@vue/shared

npm i https://pkg.pr.new/@vue/shared@13449

vue

npm i https://pkg.pr.new/vue@13449

@vue/compat

npm i https://pkg.pr.new/@vue/compat@13449

commit: b8e63f7

@@ -3082,6 +3082,7 @@ describe('e2e: Transition', () => {

// enter
await classWhenTransitionStart()
await nextFrame()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to the goal of this PR, but this test was flaky for me locally (even before the change); I see in most other places in this file nextFrame is called before transitionFinish so I added it here as well but please let me know if adding it here is incorrect

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this change is necessary. the e2e tests have passed on ci.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah fair enough, I was having some flakiness running this test locally though, even on the main branch with no code changes :/

My best guess is that the 200ms timeout used on transitionFinish in the CI environment is lenient enough to consistently pass but the 50ms timeout locally is what was causing flakiness for me. If I double the waiting period for the transitionFinish call in this test it also begins passing consistently locally for example.

I can revert this change if you'd like though

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR should fix the intended bug only and not introduce unrelated changes.

see https://github.com/vuejs/core/blob/main/.github/contributing.md#advanced-pull-request-tips

@edison1105
Copy link
Member

/ecosystem-ci run

@edison1105 edison1105 added the 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. label Jun 9, 2025
@vue-bot
Copy link
Contributor

vue-bot commented Jun 9, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
test-utils success success
primevue success success
router success success
pinia success success
quasar success success
vue-macros failure success
language-tools success success
radix-vue success success
vant success success
vuetify success failure
vue-i18n success success
vitepress success success
vue-simple-compiler success success
vite-plugin-vue success success
vueuse success success
nuxt success success

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

useTemplateRef warning appears after rollup packaging
3 participants