Skip to content

fix(useTemplateRef): handle useTemplateRef edge case with vFor #12733

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 4 commits into
base: main
Choose a base branch
from

Conversation

edison1105
Copy link
Member

@edison1105 edison1105 commented Jan 17, 2025

close #12731

the underlying problem is

const elements1 = useTemplateRef('testref') 
// instance.refs['testref'] is a shallowRef
instance.refs['testref'].value = [1]  // value is an array

const elements2 = ref() 
// instance.refs['elements2'] is a ref
instance.refs['elements2'].value = [1]  // value is a reactive array

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of template refs in lists to ensure refs collected with v-for are now reactive arrays, providing more accurate and responsive behavior in dynamic list scenarios.
  • Tests

    • Added a new test case to verify that refs collected with v-for are properly managed as reactive arrays.

Copy link

github-actions bot commented Jan 17, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 100 kB (+4 B) 38 kB (+7 B) 34.2 kB (-7 B)
vue.global.prod.js 158 kB (+4 B) 57.8 kB (+3 B) 51.4 kB (-5 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.4 kB (+32 B) 18.2 kB (+5 B) 16.6 kB (-16 B)
createApp 54.4 kB (+32 B) 21.2 kB (+12 B) 19.3 kB (+13 B)
createSSRApp 58.6 kB (+32 B) 22.9 kB (+4 B) 20.9 kB (+9 B)
defineCustomElement 59.2 kB (+32 B) 22.8 kB (+8 B) 20.7 kB (+8 B)
overall 68.4 kB (+32 B) 26.3 kB (+9 B) 24 kB (-25 B)

Copy link

pkg-pr-new bot commented Jan 17, 2025

Open in Stackblitz

@vue/compiler-core

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

@vue/compiler-sfc

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

@vue/compiler-dom

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

@vue/compiler-ssr

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

@vue/runtime-core

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

@vue/runtime-dom

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

@vue/reactivity

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

@vue/server-renderer

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

@vue/shared

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

vue

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

@vue/compat

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

commit: 2336e2a

@edison1105 edison1105 added ready to merge The PR is ready to be merged. 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. labels Jan 17, 2025
@skirtles-code
Copy link
Contributor

I'm not sure whether it would be considered a problem, but this change would also impact $refs.

@edison1105
Copy link
Member Author

I'm not sure whether it would be considered a problem, but this change would also impact $refs.

Thanks for your review. Perhaps this cannot be regarded as a problem, because this kind of behavior already exists in PROD.

@skirtles-code
Copy link
Contributor

I would be nervous about drawing any conclusions based on that example. getCurrentInstance() is undocumented, so to hit that edge case using documented APIs you'd need to mix <script setup> and the Options API. Not only is it inconsistent between DEV and PROD, it also behaves differently depending on whether you use ref() or ref([]):

It strikes me as an unintentional edge case, rather than something we should be using as precedent.


I'm not entirely clear why $refs isn't reactive, but personally I think it's a decision that should be revisited. That might also allow the implementation of useTemplateRef to be simplified too.

But, given $refs currently isn't reactive, I'd be hesitant to introduce partial reactivity in just the v-for case unless we're planning to move towards full reactivity in future.

Copy link

coderabbitai bot commented Jun 18, 2025

Walkthrough

A new test verifies that template refs collected via v-for are reactive arrays. The implementation is updated so that string refs assigned to arrays are now wrapped with shallowReactive, ensuring reactivity. No changes were made to exported APIs or public interfaces.

Changes

Files Change Summary
packages/runtime-core/tests/helpers/useTemplateRef.spec.ts Added test to verify that refs collected in v-for are reactive arrays.
packages/runtime-core/src/rendererTemplateRef.ts Updated setRef to wrap array refs with shallowReactive for string refs in template refs.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant Renderer
    participant Reactivity

    Component->>Renderer: Render elements with v-for and template ref
    Renderer->>Renderer: Collect refs for each element
    Renderer->>Reactivity: Wrap refs array with shallowReactive
    Reactivity-->>Renderer: Return reactive array
    Renderer->>Component: Assign reactive array to template ref
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure useTemplateRef returns Ref, not ShallowRef, and maintains reactivity (#12731)
Ensure collected refs in v-for are reactive arrays matching documentation (#12731)

Possibly related issues

Poem

A bunny hopped through code so neat,
Making refs in loops reactive and sweet.
With shallowReactive arrays,
Now refs update in all ways—
A hop, a test, and bugs in retreat!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
packages/runtime-core/src/rendererTemplateRef.ts (1)

126-134: Inconsistent behaviour between string refs and object refs

shallowReactive([refValue]) is created only when _isString is true.
For the _isRef branch a plain array is still assigned (ref.value = [refValue]), meaning that:

<li :ref="myShallowRef" ref_for />

will not receive a reactive array, whereas

<li ref="myKey" ref_for />

will.

Unless there is a deliberate reason to preserve this asymmetry, consider applying the same shallowReactive wrapping to the _isRef path for consistency and to avoid surprising API differences.

-            ref.value = [refValue]
+            ref.value = shallowReactive([refValue])
🧹 Nitpick comments (2)
packages/runtime-core/src/rendererTemplateRef.ts (1)

14-14: Minor: keep import list alphabetised for easier diff-scanning

shallowReactive was inserted between isRef and toRaw, breaking the previous alphabetical order of the imported symbols. A consistent ordering reduces merge-conflicts and makes future diffs easier to read.

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

76-126: Nice coverage – consider asserting isReactive(t1.value) as well

The new test correctly checks that instance.refs['refKey'] is reactive, but it never verifies that t1.value – the value returned by useTemplateRef – is the same reactive proxy. A quick extra assertion would guarantee the public API receives the reactive array you expect:

expect(t1!.value).toBe(currentInstance.refs['refKey'])
expect(isReactive(t1!.value)).toBe(true)

Adding this would catch a future regression where refs stays reactive but useTemplateRef returns a plain array.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82da43d and 2336e2a.

📒 Files selected for processing (2)
  • packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts (2 hunks)
  • packages/runtime-core/src/rendererTemplateRef.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts (3)
packages/runtime-core/src/component.ts (1)
  • currentInstance (708-708)
packages/runtime-core/src/helpers/useTemplateRef.ts (1)
  • useTemplateRef (8-40)
packages/runtime-test/src/serialize.ts (1)
  • serializeInner (22-33)

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. need discussion ready to merge The PR is ready to be merged.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

useTemplateRef returns ShallowRef instead of Ref
3 participants