Template Local Variable Binding Proposal #12323
-
Summary
Propose a new template syntax for creating local variable bindings with reactive references, similar to Vue's v-slot but more straightforward for simple variable aliasing.
Motivation
When working with deeply nested reactive objects or when we want to create local aliases for reactive data, current solutions either require script setup variables or slot syntax. A more direct syntax in template could improve code readability and reduce boilerplate.
Proposed Syntax
<template v-def="sourceData => localName"> <!-- localName is now a reactive reference to sourceData --> </template>
Example Usage
<script setup> import { ref } from 'vue' const data = ref({user: {name: 'Tom', age: 18}}) </script> <template> <template v-def="[data.user,userInfo]"> <input v-model="userInfo.name" /> <input type="number" v-model="userInfo.age" /> </template> </template>
Benefits
- More intuitive syntax for creating local variable bindings
- Maintains reactivity
- Supports two-way binding
- Reduces the need for script setup variables when only template scoping is needed
- Similar to JavaScript arrow function syntax, making it familiar to developers
Current Alternatives
Currently, developers need to either:
- Create computed properties in script setup
- Use v-slot syntax
- Use toRefs in script setup
Questions for Discussion
- Is this syntax intuitive enough?
- Should this be a built-in feature or remain as a custom directive?
- Are there potential edge cases we should consider?
- How would this interact with TypeScript type inference?
Looking forward to the community's thoughts and feedback on this proposal.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments
-
see #7218
Beta Was this translation helpful? Give feedback.
All reactions
-
Currently, Vue templates do not provide a clean built-in way to create a local alias for a value inside a template block.
As a result, I discovered this unusual workaround :
<template v-for="i in [var]">
{{ i }}
</template>
This takes advantage of v-for’s iteration aliasing, using a single-element array only to introduce a temporary variable i.
While it works, this pattern is semantically incorrect, reduces readability, and introduces unnecessary cognitive burden for teams.
I would like to propose adding a dedicated directive to provide clean, explicit template-level aliasing.
Beta Was this translation helpful? Give feedback.