实现前端开发的SKILL
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
---
|
||||
name: create-adaptable-composable
|
||||
description: Create a library-grade Vue composable that accepts maybe-reactive inputs (MaybeRef / MaybeRefOrGetter) so callers can pass a plain value, ref, or getter. Normalize inputs with toValue()/toRef() inside reactive effects (watch/watchEffect) to keep behavior predictable and reactive. Use this skill when user asks for creating adaptable or reusable composables.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: github.com/vuejs-ai
|
||||
version: "17.0.0"
|
||||
compatibility: Requires Vue 3 (or above) or Nuxt 3 (or above) project
|
||||
---
|
||||
|
||||
# Create Adaptable Composable
|
||||
|
||||
Adaptable composables are reusable functions that can accept both reactive and non-reactive inputs. This allows developers to use the composable in a variety of contexts without worrying about the reactivity of the inputs.
|
||||
|
||||
Steps to design an adaptable composable in Vue.js:
|
||||
1. Confirm the composable's purpose and API design and expected inputs/outputs.
|
||||
2. Identify inputs params that should be reactive (MaybeRef / MaybeRefOrGetter).
|
||||
3. Use `toValue()` or `toRef()` to normalize inputs inside reactive effects.
|
||||
4. Implement the core logic of the composable using Vue's reactivity APIs.
|
||||
|
||||
## Core Type Concepts
|
||||
|
||||
### Type Utilities
|
||||
|
||||
```ts
|
||||
/**
|
||||
* value or writable ref (value/ref/shallowRef/writable computed)
|
||||
*/
|
||||
export type MaybeRef<T = any> = T | Ref<T> | ShallowRef<T> | WritableComputedRef<T>;
|
||||
|
||||
/**
|
||||
* MaybeRef<T> + ComputedRef<T> + () => T
|
||||
*/
|
||||
export type MaybeRefOrGetter<T = any> = MaybeRef<T> | ComputedRef<T> | (() => T);
|
||||
```
|
||||
|
||||
### Policy and Rules
|
||||
|
||||
- Read-only, computed-friendly input: use `MaybeRefOrGetter`
|
||||
- Needs to be writable / two-way input: use `MaybeRef`
|
||||
- Parameter might be a function value (callback/predicate/comparator): do not use `MaybeRefOrGetter`, or you may accidentally invoke it as a getter.
|
||||
- DOM/Element targets: if you want computed/derived targets, use `MaybeRefOrGetter`.
|
||||
|
||||
When `MaybeRefOrGetter` or `MaybeRef` is used:
|
||||
- resolve reactive value using `toRef()` (e.g. watcher source)
|
||||
- resolve non-reactive value using `toValue()`
|
||||
|
||||
### Examples
|
||||
|
||||
Adaptable `useDocumentTitle` Composable: read-only title parameter
|
||||
|
||||
```ts
|
||||
import { watch, toRef } from 'vue'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useDocumentTitle(title: MaybeRefOrGetter<string>) {
|
||||
watch(toRef(title), (t) => {
|
||||
document.title = t
|
||||
}, { immediate: true })
|
||||
}
|
||||
```
|
||||
|
||||
Adaptable `useCounter` Composable: two-way writable count parameter
|
||||
|
||||
```ts
|
||||
import { watch, toRef } from 'vue'
|
||||
import type { MaybeRef } from 'vue'
|
||||
|
||||
function useCounter(count: MaybeRef<number>) {
|
||||
const countRef = toRef(count)
|
||||
function add() {
|
||||
countRef.value++
|
||||
}
|
||||
return { add }
|
||||
}
|
||||
```
|
||||
177
1-Vue3-Dev/.agents/skills/frontend-design/LICENSE.txt
Normal file
177
1-Vue3-Dev/.agents/skills/frontend-design/LICENSE.txt
Normal file
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
55
1-Vue3-Dev/.agents/skills/frontend-design/SKILL.md
Normal file
55
1-Vue3-Dev/.agents/skills/frontend-design/SKILL.md
Normal file
@@ -0,0 +1,55 @@
|
||||
---
|
||||
name: frontend-design
|
||||
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Frontend Design
|
||||
|
||||
Approach this as the design lead at a small studio known for giving every client a visual identity that could not be mistaken for anyone else's. This client has already rejected proposals that felt templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take one real aesthetic risk you can justify.
|
||||
|
||||
## Ground it in the subject
|
||||
|
||||
If the brief does not pin down what the product or subject is, pin it yourself before designing: name one concrete subject, its audience, and the page's single job, and state your choice. If there's any information in your memory about the human's preferences, context about what they're building, or designs you've made before – use that as a hint. The subject's own world, its materials, instruments, artifacts, and vernacular, is where distinctive choices come from. Build with the brief's real content and subject matter throughout.
|
||||
|
||||
## Design principles
|
||||
|
||||
For web designs, the hero is a thesis. Open with the most characteristic thing in the subject's world, in whatever form makes sense for it: a headline, an image, an animation, a live demo, an interactive moment. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the template answer, only use if that's truly the best option.
|
||||
|
||||
Typography carries the personality of the page. Pair the display and body faces deliberately, not the same families you would reach for on any other project, and set a clear type scale with intentional weights, widths, and spacing. Make the type treatment itself a memorable part of the design, not a neutral delivery vehicle for the content.
|
||||
|
||||
Structure is information. Structural devices, numbering, eyebrows, dividers, labels, should encode something true about the content, not decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence - like a real process or a typed timeline where order carries information the reader needs. Question if choices like numbered markers actually make sense before incorporating them.
|
||||
|
||||
Leverage motion deliberately. Think about where and if animation can serve the subject: a page-load sequence, a scroll-triggered reveal, hover micro-interactions, ambient atmosphere. An orchestrated moment usually lands harder than scattered effects; choose what the direction calls for. However, sometimes less is more, and extra animation contributes to the feeling that the design is AI-generated.
|
||||
|
||||
Match complexity to the vision. Maximalist directions need elaborate execution; minimal directions need precision in spacing, type, and detail. Elegance is executing the chosen vision well.
|
||||
|
||||
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
|
||||
|
||||
## Process: brainstorm, explore, plan, critique, build, critique again
|
||||
|
||||
For calibration: AI-generated design right now clusters around three looks: (1) a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta accent; (2) a near-black background with a single bright acid-green or vermilion accent; (3) a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns. All three are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. Just like a human designer who's hired, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
|
||||
|
||||
Work in two passes. First, brainstorm a short design plan based on the human's design brief: create a compact token system with color, type, layout, and signature. Color: describe the palette as 4–6 named hex values. Type: the typefaces for 2+ roles (a characterful display face that's used with restraint, a complementary body face, and a utility face for captions or data if needed). Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Signature: the single unique element this page will be remembered by that embodies the brief in an appropriate way.
|
||||
|
||||
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan exactly and deriving every color and type decision from it.
|
||||
|
||||
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and a element-based selector like .cta). This can happen often with paddings/margins between sections.
|
||||
|
||||
Try to do a lot of this planning and iteration in your thinking, and only show ideas to the user when you have higher confidence it'll delight them.
|
||||
|
||||
## Restraint and self-critique
|
||||
|
||||
Spend your boldness in one place. Let the signature element be the one memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Not taking a risk can be a risk itself! Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected. Critique your own work as you build, taking screenshots if your environment supports it – a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creators have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
|
||||
|
||||
## More on writing in design
|
||||
|
||||
Words appear in a design for one reason: to make it easier to understand, and therefore easier to use. They are design material, not decoration. Bring the same intentionality to copy that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
|
||||
|
||||
Write from the end user's side of the screen. Name things by what people control and recognize, never by how the system is built. A person manages notifications, not webhook config. Describe what something does in plain terms rather than selling it. Being specific is always better than being clever.
|
||||
|
||||
Use active voice as default. A control should say exactly what happens when it's used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
|
||||
|
||||
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
|
||||
|
||||
Keep the register conversational and tuned: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each element do exactly one job. A label labels, an example demonstrates, and nothing quietly does double duty.
|
||||
202
1-Vue3-Dev/.agents/skills/skill-creator/LICENSE.txt
Normal file
202
1-Vue3-Dev/.agents/skills/skill-creator/LICENSE.txt
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Anthropic, PBC.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
485
1-Vue3-Dev/.agents/skills/skill-creator/SKILL.md
Normal file
485
1-Vue3-Dev/.agents/skills/skill-creator/SKILL.md
Normal file
@@ -0,0 +1,485 @@
|
||||
---
|
||||
name: skill-creator
|
||||
description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
|
||||
---
|
||||
|
||||
# Skill Creator
|
||||
|
||||
A skill for creating new skills and iteratively improving them.
|
||||
|
||||
At a high level, the process of creating a skill goes like this:
|
||||
|
||||
- Decide what you want the skill to do and roughly how it should do it
|
||||
- Write a draft of the skill
|
||||
- Create a few test prompts and run claude-with-access-to-the-skill on them
|
||||
- Help the user evaluate the results both qualitatively and quantitatively
|
||||
- While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist)
|
||||
- Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics
|
||||
- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks)
|
||||
- Repeat until you're satisfied
|
||||
- Expand the test set and try again at larger scale
|
||||
|
||||
Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat.
|
||||
|
||||
On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop.
|
||||
|
||||
Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead.
|
||||
|
||||
Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill.
|
||||
|
||||
Cool? Cool.
|
||||
|
||||
## Communicating with the user
|
||||
|
||||
The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate.
|
||||
|
||||
So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea:
|
||||
|
||||
- "evaluation" and "benchmark" are borderline, but OK
|
||||
- for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them
|
||||
|
||||
It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it.
|
||||
|
||||
---
|
||||
|
||||
## Creating a skill
|
||||
|
||||
### Capture Intent
|
||||
|
||||
Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step.
|
||||
|
||||
1. What should this skill enable Claude to do?
|
||||
2. When should this skill trigger? (what user phrases/contexts)
|
||||
3. What's the expected output format?
|
||||
4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide.
|
||||
|
||||
### Interview and Research
|
||||
|
||||
Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out.
|
||||
|
||||
Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user.
|
||||
|
||||
### Write the SKILL.md
|
||||
|
||||
Based on the user interview, fill in these components:
|
||||
|
||||
- **name**: Skill identifier
|
||||
- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'"
|
||||
- **compatibility**: Required tools, dependencies (optional, rarely needed)
|
||||
- **the rest of the skill :)**
|
||||
|
||||
### Skill Writing Guide
|
||||
|
||||
#### Anatomy of a Skill
|
||||
|
||||
```
|
||||
skill-name/
|
||||
├── SKILL.md (required)
|
||||
│ ├── YAML frontmatter (name, description required)
|
||||
│ └── Markdown instructions
|
||||
└── Bundled Resources (optional)
|
||||
├── scripts/ - Executable code for deterministic/repetitive tasks
|
||||
├── references/ - Docs loaded into context as needed
|
||||
└── assets/ - Files used in output (templates, icons, fonts)
|
||||
```
|
||||
|
||||
#### Progressive Disclosure
|
||||
|
||||
Skills use a three-level loading system:
|
||||
1. **Metadata** (name + description) - Always in context (~100 words)
|
||||
2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal)
|
||||
3. **Bundled resources** - As needed (unlimited, scripts can execute without loading)
|
||||
|
||||
These word counts are approximate and you can feel free to go longer if needed.
|
||||
|
||||
**Key patterns:**
|
||||
- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up.
|
||||
- Reference files clearly from SKILL.md with guidance on when to read them
|
||||
- For large reference files (>300 lines), include a table of contents
|
||||
|
||||
**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant:
|
||||
```
|
||||
cloud-deploy/
|
||||
├── SKILL.md (workflow + selection)
|
||||
└── references/
|
||||
├── aws.md
|
||||
├── gcp.md
|
||||
└── azure.md
|
||||
```
|
||||
Claude reads only the relevant reference file.
|
||||
|
||||
#### Principle of Lack of Surprise
|
||||
|
||||
This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though.
|
||||
|
||||
#### Writing Patterns
|
||||
|
||||
Prefer using the imperative form in instructions.
|
||||
|
||||
**Defining output formats** - You can do it like this:
|
||||
```markdown
|
||||
## Report structure
|
||||
ALWAYS use this exact template:
|
||||
# [Title]
|
||||
## Executive summary
|
||||
## Key findings
|
||||
## Recommendations
|
||||
```
|
||||
|
||||
**Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little):
|
||||
```markdown
|
||||
## Commit message format
|
||||
**Example 1:**
|
||||
Input: Added user authentication with JWT tokens
|
||||
Output: feat(auth): implement JWT-based authentication
|
||||
```
|
||||
|
||||
### Writing Style
|
||||
|
||||
Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it.
|
||||
|
||||
### Test Cases
|
||||
|
||||
After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them.
|
||||
|
||||
Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress.
|
||||
|
||||
```json
|
||||
{
|
||||
"skill_name": "example-skill",
|
||||
"evals": [
|
||||
{
|
||||
"id": 1,
|
||||
"prompt": "User's task prompt",
|
||||
"expected_output": "Description of expected result",
|
||||
"files": []
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later).
|
||||
|
||||
## Running and evaluating test cases
|
||||
|
||||
This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill.
|
||||
|
||||
Put results in `<skill-name>-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go.
|
||||
|
||||
### Step 1: Spawn all runs (with-skill AND baseline) in the same turn
|
||||
|
||||
For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time.
|
||||
|
||||
**With-skill run:**
|
||||
|
||||
```
|
||||
Execute this task:
|
||||
- Skill path: <path-to-skill>
|
||||
- Task: <eval prompt>
|
||||
- Input files: <eval files if any, or "none">
|
||||
- Save outputs to: <workspace>/iteration-<N>/eval-<ID>/with_skill/outputs/
|
||||
- Outputs to save: <what the user cares about — e.g., "the .docx file", "the final CSV">
|
||||
```
|
||||
|
||||
**Baseline run** (same prompt, but the baseline depends on context):
|
||||
- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`.
|
||||
- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r <skill-path> <workspace>/skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`.
|
||||
|
||||
Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations.
|
||||
|
||||
```json
|
||||
{
|
||||
"eval_id": 0,
|
||||
"eval_name": "descriptive-name-here",
|
||||
"prompt": "The user's task prompt",
|
||||
"assertions": []
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: While runs are in progress, draft assertions
|
||||
|
||||
Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check.
|
||||
|
||||
Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment.
|
||||
|
||||
Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark.
|
||||
|
||||
### Step 3: As runs complete, capture timing data
|
||||
|
||||
When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory:
|
||||
|
||||
```json
|
||||
{
|
||||
"total_tokens": 84852,
|
||||
"duration_ms": 23332,
|
||||
"total_duration_seconds": 23.3
|
||||
}
|
||||
```
|
||||
|
||||
This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them.
|
||||
|
||||
### Step 4: Grade, aggregate, and launch the viewer
|
||||
|
||||
Once all runs are done:
|
||||
|
||||
1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations.
|
||||
|
||||
2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory:
|
||||
```bash
|
||||
python -m scripts.aggregate_benchmark <workspace>/iteration-N --skill-name <name>
|
||||
```
|
||||
This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects.
|
||||
Put each with_skill version before its baseline counterpart.
|
||||
|
||||
3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs.
|
||||
|
||||
4. **Launch the viewer** with both qualitative outputs and quantitative data:
|
||||
```bash
|
||||
nohup python <skill-creator-path>/eval-viewer/generate_review.py \
|
||||
<workspace>/iteration-N \
|
||||
--skill-name "my-skill" \
|
||||
--benchmark <workspace>/iteration-N/benchmark.json \
|
||||
> /dev/null 2>&1 &
|
||||
VIEWER_PID=$!
|
||||
```
|
||||
For iteration 2+, also pass `--previous-workspace <workspace>/iteration-<N-1>`.
|
||||
|
||||
**Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up.
|
||||
|
||||
Note: please use generate_review.py to create the viewer; there's no need to write custom HTML.
|
||||
|
||||
5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know."
|
||||
|
||||
### What the user sees in the viewer
|
||||
|
||||
The "Outputs" tab shows one test case at a time:
|
||||
- **Prompt**: the task that was given
|
||||
- **Output**: the files the skill produced, rendered inline where possible
|
||||
- **Previous Output** (iteration 2+): collapsed section showing last iteration's output
|
||||
- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail
|
||||
- **Feedback**: a textbox that auto-saves as they type
|
||||
- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox
|
||||
|
||||
The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations.
|
||||
|
||||
Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`.
|
||||
|
||||
### Step 5: Read the feedback
|
||||
|
||||
When the user tells you they're done, read `feedback.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"reviews": [
|
||||
{"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."},
|
||||
{"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."},
|
||||
{"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."}
|
||||
],
|
||||
"status": "complete"
|
||||
}
|
||||
```
|
||||
|
||||
Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints.
|
||||
|
||||
Kill the viewer server when you're done with it:
|
||||
|
||||
```bash
|
||||
kill $VIEWER_PID 2>/dev/null
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Improving the skill
|
||||
|
||||
This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback.
|
||||
|
||||
### How to think about improvements
|
||||
|
||||
1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great.
|
||||
|
||||
2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens.
|
||||
|
||||
3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach.
|
||||
|
||||
4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel.
|
||||
|
||||
This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need.
|
||||
|
||||
### The iteration loop
|
||||
|
||||
After improving the skill:
|
||||
|
||||
1. Apply your improvements to the skill
|
||||
2. Rerun all test cases into a new `iteration-<N+1>/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration.
|
||||
3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration
|
||||
4. Wait for the user to review and tell you they're done
|
||||
5. Read the new feedback, improve again, repeat
|
||||
|
||||
Keep going until:
|
||||
- The user says they're happy
|
||||
- The feedback is all empty (everything looks good)
|
||||
- You're not making meaningful progress
|
||||
|
||||
---
|
||||
|
||||
## Advanced: Blind comparison
|
||||
|
||||
For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won.
|
||||
|
||||
This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient.
|
||||
|
||||
---
|
||||
|
||||
## Description Optimization
|
||||
|
||||
The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy.
|
||||
|
||||
### Step 1: Generate trigger eval queries
|
||||
|
||||
Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON:
|
||||
|
||||
```json
|
||||
[
|
||||
{"query": "the user prompt", "should_trigger": true},
|
||||
{"query": "another prompt", "should_trigger": false}
|
||||
]
|
||||
```
|
||||
|
||||
The queries must be realistic and something a Claude Code or Claude.ai user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them).
|
||||
|
||||
Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"`
|
||||
|
||||
Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"`
|
||||
|
||||
For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win.
|
||||
|
||||
For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate.
|
||||
|
||||
The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky.
|
||||
|
||||
### Step 2: Review with user
|
||||
|
||||
Present the eval set to the user for review using the HTML template:
|
||||
|
||||
1. Read the template from `assets/eval_review.html`
|
||||
2. Replace the placeholders:
|
||||
- `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment)
|
||||
- `__SKILL_NAME_PLACEHOLDER__` → the skill's name
|
||||
- `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description
|
||||
3. Write to a temp file (e.g., `/tmp/eval_review_<skill-name>.html`) and open it: `open /tmp/eval_review_<skill-name>.html`
|
||||
4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set"
|
||||
5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`)
|
||||
|
||||
This step matters — bad eval queries lead to bad descriptions.
|
||||
|
||||
### Step 3: Run the optimization loop
|
||||
|
||||
Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically."
|
||||
|
||||
Save the eval set to the workspace, then run in the background:
|
||||
|
||||
```bash
|
||||
python -m scripts.run_loop \
|
||||
--eval-set <path-to-trigger-eval.json> \
|
||||
--skill-path <path-to-skill> \
|
||||
--model <model-id-powering-this-session> \
|
||||
--max-iterations 5 \
|
||||
--verbose
|
||||
```
|
||||
|
||||
Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences.
|
||||
|
||||
While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like.
|
||||
|
||||
This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting.
|
||||
|
||||
### How skill triggering works
|
||||
|
||||
Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches.
|
||||
|
||||
This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality.
|
||||
|
||||
### Step 4: Apply the result
|
||||
|
||||
Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores.
|
||||
|
||||
---
|
||||
|
||||
### Package and Present (only if `present_files` tool is available)
|
||||
|
||||
Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user:
|
||||
|
||||
```bash
|
||||
python -m scripts.package_skill <path/to/skill-folder>
|
||||
```
|
||||
|
||||
After packaging, direct the user to the resulting `.skill` file path so they can install it.
|
||||
|
||||
---
|
||||
|
||||
## Claude.ai-specific instructions
|
||||
|
||||
In Claude.ai, the core workflow is the same (draft → test → review → improve → repeat), but because Claude.ai doesn't have subagents, some mechanics change. Here's what to adapt:
|
||||
|
||||
**Running test cases**: No subagents means no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested.
|
||||
|
||||
**Reviewing results**: If you can't open a browser (e.g., Claude.ai's VM has no display, or you're on a remote server), skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: "How does this look? Anything you'd change?"
|
||||
|
||||
**Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user.
|
||||
|
||||
**The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one.
|
||||
|
||||
**Description optimization**: This section requires the `claude` CLI tool (specifically `claude -p`) which is only available in Claude Code. Skip it if you're on Claude.ai.
|
||||
|
||||
**Blind comparison**: Requires subagents. Skip it.
|
||||
|
||||
**Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file.
|
||||
|
||||
**Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. In this case:
|
||||
- **Preserve the original name.** Note the skill's directory name and `name` frontmatter field -- use them unchanged. E.g., if the installed skill is `research-helper`, output `research-helper.skill` (not `research-helper-v2`).
|
||||
- **Copy to a writeable location before editing.** The installed skill path may be read-only. Copy to `/tmp/skill-name/`, edit there, and package from the copy.
|
||||
- **If packaging manually, stage in `/tmp/` first**, then copy to the output directory -- direct writes may fail due to permissions.
|
||||
|
||||
---
|
||||
|
||||
## Cowork-Specific Instructions
|
||||
|
||||
If you're in Cowork, the main things to know are:
|
||||
|
||||
- You have subagents, so the main workflow (spawn test cases in parallel, run baselines, grade, etc.) all works. (However, if you run into severe problems with timeouts, it's OK to run the test prompts in series rather than parallel.)
|
||||
- You don't have a browser or display, so when generating the eval viewer, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Then proffer a link that the user can click to open the HTML in their browser.
|
||||
- For whatever reason, the Cowork setup seems to disincline Claude from generating the eval viewer after running the tests, so just to reiterate: whether you're in Cowork or in Claude Code, after running tests, you should always generate the eval viewer for the human to look at examples before revising the skill yourself and trying to make corrections, using `generate_review.py` (not writing your own boutique html code). Sorry in advance but I'm gonna go all caps here: GENERATE THE EVAL VIEWER *BEFORE* evaluating inputs yourself. You want to get them in front of the human ASAP!
|
||||
- Feedback works differently: since there's no running server, the viewer's "Submit All Reviews" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first).
|
||||
- Packaging works — `package_skill.py` just needs Python and a filesystem.
|
||||
- Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape.
|
||||
- **Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. Follow the update guidance in the claude.ai section above.
|
||||
|
||||
---
|
||||
|
||||
## Reference files
|
||||
|
||||
The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent.
|
||||
|
||||
- `agents/grader.md` — How to evaluate assertions against outputs
|
||||
- `agents/comparator.md` — How to do blind A/B comparison between two outputs
|
||||
- `agents/analyzer.md` — How to analyze why one version beat another
|
||||
|
||||
The references/ directory has additional documentation:
|
||||
- `references/schemas.md` — JSON structures for evals.json, grading.json, etc.
|
||||
|
||||
---
|
||||
|
||||
Repeating one more time the core loop here for emphasis:
|
||||
|
||||
- Figure out what the skill is about
|
||||
- Draft or edit the skill
|
||||
- Run claude-with-access-to-the-skill on test prompts
|
||||
- With the user, evaluate the outputs:
|
||||
- Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them
|
||||
- Run quantitative evals
|
||||
- Repeat until you and the user are satisfied
|
||||
- Package the final skill and return it to the user.
|
||||
|
||||
Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens.
|
||||
|
||||
Good luck!
|
||||
274
1-Vue3-Dev/.agents/skills/skill-creator/agents/analyzer.md
Normal file
274
1-Vue3-Dev/.agents/skills/skill-creator/agents/analyzer.md
Normal file
@@ -0,0 +1,274 @@
|
||||
# Post-hoc Analyzer Agent
|
||||
|
||||
Analyze blind comparison results to understand WHY the winner won and generate improvement suggestions.
|
||||
|
||||
## Role
|
||||
|
||||
After the blind comparator determines a winner, the Post-hoc Analyzer "unblids" the results by examining the skills and transcripts. The goal is to extract actionable insights: what made the winner better, and how can the loser be improved?
|
||||
|
||||
## Inputs
|
||||
|
||||
You receive these parameters in your prompt:
|
||||
|
||||
- **winner**: "A" or "B" (from blind comparison)
|
||||
- **winner_skill_path**: Path to the skill that produced the winning output
|
||||
- **winner_transcript_path**: Path to the execution transcript for the winner
|
||||
- **loser_skill_path**: Path to the skill that produced the losing output
|
||||
- **loser_transcript_path**: Path to the execution transcript for the loser
|
||||
- **comparison_result_path**: Path to the blind comparator's output JSON
|
||||
- **output_path**: Where to save the analysis results
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Read Comparison Result
|
||||
|
||||
1. Read the blind comparator's output at comparison_result_path
|
||||
2. Note the winning side (A or B), the reasoning, and any scores
|
||||
3. Understand what the comparator valued in the winning output
|
||||
|
||||
### Step 2: Read Both Skills
|
||||
|
||||
1. Read the winner skill's SKILL.md and key referenced files
|
||||
2. Read the loser skill's SKILL.md and key referenced files
|
||||
3. Identify structural differences:
|
||||
- Instructions clarity and specificity
|
||||
- Script/tool usage patterns
|
||||
- Example coverage
|
||||
- Edge case handling
|
||||
|
||||
### Step 3: Read Both Transcripts
|
||||
|
||||
1. Read the winner's transcript
|
||||
2. Read the loser's transcript
|
||||
3. Compare execution patterns:
|
||||
- How closely did each follow their skill's instructions?
|
||||
- What tools were used differently?
|
||||
- Where did the loser diverge from optimal behavior?
|
||||
- Did either encounter errors or make recovery attempts?
|
||||
|
||||
### Step 4: Analyze Instruction Following
|
||||
|
||||
For each transcript, evaluate:
|
||||
- Did the agent follow the skill's explicit instructions?
|
||||
- Did the agent use the skill's provided tools/scripts?
|
||||
- Were there missed opportunities to leverage skill content?
|
||||
- Did the agent add unnecessary steps not in the skill?
|
||||
|
||||
Score instruction following 1-10 and note specific issues.
|
||||
|
||||
### Step 5: Identify Winner Strengths
|
||||
|
||||
Determine what made the winner better:
|
||||
- Clearer instructions that led to better behavior?
|
||||
- Better scripts/tools that produced better output?
|
||||
- More comprehensive examples that guided edge cases?
|
||||
- Better error handling guidance?
|
||||
|
||||
Be specific. Quote from skills/transcripts where relevant.
|
||||
|
||||
### Step 6: Identify Loser Weaknesses
|
||||
|
||||
Determine what held the loser back:
|
||||
- Ambiguous instructions that led to suboptimal choices?
|
||||
- Missing tools/scripts that forced workarounds?
|
||||
- Gaps in edge case coverage?
|
||||
- Poor error handling that caused failures?
|
||||
|
||||
### Step 7: Generate Improvement Suggestions
|
||||
|
||||
Based on the analysis, produce actionable suggestions for improving the loser skill:
|
||||
- Specific instruction changes to make
|
||||
- Tools/scripts to add or modify
|
||||
- Examples to include
|
||||
- Edge cases to address
|
||||
|
||||
Prioritize by impact. Focus on changes that would have changed the outcome.
|
||||
|
||||
### Step 8: Write Analysis Results
|
||||
|
||||
Save structured analysis to `{output_path}`.
|
||||
|
||||
## Output Format
|
||||
|
||||
Write a JSON file with this structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"comparison_summary": {
|
||||
"winner": "A",
|
||||
"winner_skill": "path/to/winner/skill",
|
||||
"loser_skill": "path/to/loser/skill",
|
||||
"comparator_reasoning": "Brief summary of why comparator chose winner"
|
||||
},
|
||||
"winner_strengths": [
|
||||
"Clear step-by-step instructions for handling multi-page documents",
|
||||
"Included validation script that caught formatting errors",
|
||||
"Explicit guidance on fallback behavior when OCR fails"
|
||||
],
|
||||
"loser_weaknesses": [
|
||||
"Vague instruction 'process the document appropriately' led to inconsistent behavior",
|
||||
"No script for validation, agent had to improvise and made errors",
|
||||
"No guidance on OCR failure, agent gave up instead of trying alternatives"
|
||||
],
|
||||
"instruction_following": {
|
||||
"winner": {
|
||||
"score": 9,
|
||||
"issues": [
|
||||
"Minor: skipped optional logging step"
|
||||
]
|
||||
},
|
||||
"loser": {
|
||||
"score": 6,
|
||||
"issues": [
|
||||
"Did not use the skill's formatting template",
|
||||
"Invented own approach instead of following step 3",
|
||||
"Missed the 'always validate output' instruction"
|
||||
]
|
||||
}
|
||||
},
|
||||
"improvement_suggestions": [
|
||||
{
|
||||
"priority": "high",
|
||||
"category": "instructions",
|
||||
"suggestion": "Replace 'process the document appropriately' with explicit steps: 1) Extract text, 2) Identify sections, 3) Format per template",
|
||||
"expected_impact": "Would eliminate ambiguity that caused inconsistent behavior"
|
||||
},
|
||||
{
|
||||
"priority": "high",
|
||||
"category": "tools",
|
||||
"suggestion": "Add validate_output.py script similar to winner skill's validation approach",
|
||||
"expected_impact": "Would catch formatting errors before final output"
|
||||
},
|
||||
{
|
||||
"priority": "medium",
|
||||
"category": "error_handling",
|
||||
"suggestion": "Add fallback instructions: 'If OCR fails, try: 1) different resolution, 2) image preprocessing, 3) manual extraction'",
|
||||
"expected_impact": "Would prevent early failure on difficult documents"
|
||||
}
|
||||
],
|
||||
"transcript_insights": {
|
||||
"winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script -> Fixed 2 issues -> Produced output",
|
||||
"loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods -> No validation -> Output had errors"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Guidelines
|
||||
|
||||
- **Be specific**: Quote from skills and transcripts, don't just say "instructions were unclear"
|
||||
- **Be actionable**: Suggestions should be concrete changes, not vague advice
|
||||
- **Focus on skill improvements**: The goal is to improve the losing skill, not critique the agent
|
||||
- **Prioritize by impact**: Which changes would most likely have changed the outcome?
|
||||
- **Consider causation**: Did the skill weakness actually cause the worse output, or is it incidental?
|
||||
- **Stay objective**: Analyze what happened, don't editorialize
|
||||
- **Think about generalization**: Would this improvement help on other evals too?
|
||||
|
||||
## Categories for Suggestions
|
||||
|
||||
Use these categories to organize improvement suggestions:
|
||||
|
||||
| Category | Description |
|
||||
|----------|-------------|
|
||||
| `instructions` | Changes to the skill's prose instructions |
|
||||
| `tools` | Scripts, templates, or utilities to add/modify |
|
||||
| `examples` | Example inputs/outputs to include |
|
||||
| `error_handling` | Guidance for handling failures |
|
||||
| `structure` | Reorganization of skill content |
|
||||
| `references` | External docs or resources to add |
|
||||
|
||||
## Priority Levels
|
||||
|
||||
- **high**: Would likely change the outcome of this comparison
|
||||
- **medium**: Would improve quality but may not change win/loss
|
||||
- **low**: Nice to have, marginal improvement
|
||||
|
||||
---
|
||||
|
||||
# Analyzing Benchmark Results
|
||||
|
||||
When analyzing benchmark results, the analyzer's purpose is to **surface patterns and anomalies** across multiple runs, not suggest skill improvements.
|
||||
|
||||
## Role
|
||||
|
||||
Review all benchmark run results and generate freeform notes that help the user understand skill performance. Focus on patterns that wouldn't be visible from aggregate metrics alone.
|
||||
|
||||
## Inputs
|
||||
|
||||
You receive these parameters in your prompt:
|
||||
|
||||
- **benchmark_data_path**: Path to the in-progress benchmark.json with all run results
|
||||
- **skill_path**: Path to the skill being benchmarked
|
||||
- **output_path**: Where to save the notes (as JSON array of strings)
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Read Benchmark Data
|
||||
|
||||
1. Read the benchmark.json containing all run results
|
||||
2. Note the configurations tested (with_skill, without_skill)
|
||||
3. Understand the run_summary aggregates already calculated
|
||||
|
||||
### Step 2: Analyze Per-Assertion Patterns
|
||||
|
||||
For each expectation across all runs:
|
||||
- Does it **always pass** in both configurations? (may not differentiate skill value)
|
||||
- Does it **always fail** in both configurations? (may be broken or beyond capability)
|
||||
- Does it **always pass with skill but fail without**? (skill clearly adds value here)
|
||||
- Does it **always fail with skill but pass without**? (skill may be hurting)
|
||||
- Is it **highly variable**? (flaky expectation or non-deterministic behavior)
|
||||
|
||||
### Step 3: Analyze Cross-Eval Patterns
|
||||
|
||||
Look for patterns across evals:
|
||||
- Are certain eval types consistently harder/easier?
|
||||
- Do some evals show high variance while others are stable?
|
||||
- Are there surprising results that contradict expectations?
|
||||
|
||||
### Step 4: Analyze Metrics Patterns
|
||||
|
||||
Look at time_seconds, tokens, tool_calls:
|
||||
- Does the skill significantly increase execution time?
|
||||
- Is there high variance in resource usage?
|
||||
- Are there outlier runs that skew the aggregates?
|
||||
|
||||
### Step 5: Generate Notes
|
||||
|
||||
Write freeform observations as a list of strings. Each note should:
|
||||
- State a specific observation
|
||||
- Be grounded in the data (not speculation)
|
||||
- Help the user understand something the aggregate metrics don't show
|
||||
|
||||
Examples:
|
||||
- "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value"
|
||||
- "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure that may be flaky"
|
||||
- "Without-skill runs consistently fail on table extraction expectations (0% pass rate)"
|
||||
- "Skill adds 13s average execution time but improves pass rate by 50%"
|
||||
- "Token usage is 80% higher with skill, primarily due to script output parsing"
|
||||
- "All 3 without-skill runs for eval 1 produced empty output"
|
||||
|
||||
### Step 6: Write Notes
|
||||
|
||||
Save notes to `{output_path}` as a JSON array of strings:
|
||||
|
||||
```json
|
||||
[
|
||||
"Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value",
|
||||
"Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure",
|
||||
"Without-skill runs consistently fail on table extraction expectations",
|
||||
"Skill adds 13s average execution time but improves pass rate by 50%"
|
||||
]
|
||||
```
|
||||
|
||||
## Guidelines
|
||||
|
||||
**DO:**
|
||||
- Report what you observe in the data
|
||||
- Be specific about which evals, expectations, or runs you're referring to
|
||||
- Note patterns that aggregate metrics would hide
|
||||
- Provide context that helps interpret the numbers
|
||||
|
||||
**DO NOT:**
|
||||
- Suggest improvements to the skill (that's for the improvement step, not benchmarking)
|
||||
- Make subjective quality judgments ("the output was good/bad")
|
||||
- Speculate about causes without evidence
|
||||
- Repeat information already in the run_summary aggregates
|
||||
202
1-Vue3-Dev/.agents/skills/skill-creator/agents/comparator.md
Normal file
202
1-Vue3-Dev/.agents/skills/skill-creator/agents/comparator.md
Normal file
@@ -0,0 +1,202 @@
|
||||
# Blind Comparator Agent
|
||||
|
||||
Compare two outputs WITHOUT knowing which skill produced them.
|
||||
|
||||
## Role
|
||||
|
||||
The Blind Comparator judges which output better accomplishes the eval task. You receive two outputs labeled A and B, but you do NOT know which skill produced which. This prevents bias toward a particular skill or approach.
|
||||
|
||||
Your judgment is based purely on output quality and task completion.
|
||||
|
||||
## Inputs
|
||||
|
||||
You receive these parameters in your prompt:
|
||||
|
||||
- **output_a_path**: Path to the first output file or directory
|
||||
- **output_b_path**: Path to the second output file or directory
|
||||
- **eval_prompt**: The original task/prompt that was executed
|
||||
- **expectations**: List of expectations to check (optional - may be empty)
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Read Both Outputs
|
||||
|
||||
1. Examine output A (file or directory)
|
||||
2. Examine output B (file or directory)
|
||||
3. Note the type, structure, and content of each
|
||||
4. If outputs are directories, examine all relevant files inside
|
||||
|
||||
### Step 2: Understand the Task
|
||||
|
||||
1. Read the eval_prompt carefully
|
||||
2. Identify what the task requires:
|
||||
- What should be produced?
|
||||
- What qualities matter (accuracy, completeness, format)?
|
||||
- What would distinguish a good output from a poor one?
|
||||
|
||||
### Step 3: Generate Evaluation Rubric
|
||||
|
||||
Based on the task, generate a rubric with two dimensions:
|
||||
|
||||
**Content Rubric** (what the output contains):
|
||||
| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |
|
||||
|-----------|----------|----------------|---------------|
|
||||
| Correctness | Major errors | Minor errors | Fully correct |
|
||||
| Completeness | Missing key elements | Mostly complete | All elements present |
|
||||
| Accuracy | Significant inaccuracies | Minor inaccuracies | Accurate throughout |
|
||||
|
||||
**Structure Rubric** (how the output is organized):
|
||||
| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |
|
||||
|-----------|----------|----------------|---------------|
|
||||
| Organization | Disorganized | Reasonably organized | Clear, logical structure |
|
||||
| Formatting | Inconsistent/broken | Mostly consistent | Professional, polished |
|
||||
| Usability | Difficult to use | Usable with effort | Easy to use |
|
||||
|
||||
Adapt criteria to the specific task. For example:
|
||||
- PDF form → "Field alignment", "Text readability", "Data placement"
|
||||
- Document → "Section structure", "Heading hierarchy", "Paragraph flow"
|
||||
- Data output → "Schema correctness", "Data types", "Completeness"
|
||||
|
||||
### Step 4: Evaluate Each Output Against the Rubric
|
||||
|
||||
For each output (A and B):
|
||||
|
||||
1. **Score each criterion** on the rubric (1-5 scale)
|
||||
2. **Calculate dimension totals**: Content score, Structure score
|
||||
3. **Calculate overall score**: Average of dimension scores, scaled to 1-10
|
||||
|
||||
### Step 5: Check Assertions (if provided)
|
||||
|
||||
If expectations are provided:
|
||||
|
||||
1. Check each expectation against output A
|
||||
2. Check each expectation against output B
|
||||
3. Count pass rates for each output
|
||||
4. Use expectation scores as secondary evidence (not the primary decision factor)
|
||||
|
||||
### Step 6: Determine the Winner
|
||||
|
||||
Compare A and B based on (in priority order):
|
||||
|
||||
1. **Primary**: Overall rubric score (content + structure)
|
||||
2. **Secondary**: Assertion pass rates (if applicable)
|
||||
3. **Tiebreaker**: If truly equal, declare a TIE
|
||||
|
||||
Be decisive - ties should be rare. One output is usually better, even if marginally.
|
||||
|
||||
### Step 7: Write Comparison Results
|
||||
|
||||
Save results to a JSON file at the path specified (or `comparison.json` if not specified).
|
||||
|
||||
## Output Format
|
||||
|
||||
Write a JSON file with this structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"winner": "A",
|
||||
"reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.",
|
||||
"rubric": {
|
||||
"A": {
|
||||
"content": {
|
||||
"correctness": 5,
|
||||
"completeness": 5,
|
||||
"accuracy": 4
|
||||
},
|
||||
"structure": {
|
||||
"organization": 4,
|
||||
"formatting": 5,
|
||||
"usability": 4
|
||||
},
|
||||
"content_score": 4.7,
|
||||
"structure_score": 4.3,
|
||||
"overall_score": 9.0
|
||||
},
|
||||
"B": {
|
||||
"content": {
|
||||
"correctness": 3,
|
||||
"completeness": 2,
|
||||
"accuracy": 3
|
||||
},
|
||||
"structure": {
|
||||
"organization": 3,
|
||||
"formatting": 2,
|
||||
"usability": 3
|
||||
},
|
||||
"content_score": 2.7,
|
||||
"structure_score": 2.7,
|
||||
"overall_score": 5.4
|
||||
}
|
||||
},
|
||||
"output_quality": {
|
||||
"A": {
|
||||
"score": 9,
|
||||
"strengths": ["Complete solution", "Well-formatted", "All fields present"],
|
||||
"weaknesses": ["Minor style inconsistency in header"]
|
||||
},
|
||||
"B": {
|
||||
"score": 5,
|
||||
"strengths": ["Readable output", "Correct basic structure"],
|
||||
"weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"]
|
||||
}
|
||||
},
|
||||
"expectation_results": {
|
||||
"A": {
|
||||
"passed": 4,
|
||||
"total": 5,
|
||||
"pass_rate": 0.80,
|
||||
"details": [
|
||||
{"text": "Output includes name", "passed": true},
|
||||
{"text": "Output includes date", "passed": true},
|
||||
{"text": "Format is PDF", "passed": true},
|
||||
{"text": "Contains signature", "passed": false},
|
||||
{"text": "Readable text", "passed": true}
|
||||
]
|
||||
},
|
||||
"B": {
|
||||
"passed": 3,
|
||||
"total": 5,
|
||||
"pass_rate": 0.60,
|
||||
"details": [
|
||||
{"text": "Output includes name", "passed": true},
|
||||
{"text": "Output includes date", "passed": false},
|
||||
{"text": "Format is PDF", "passed": true},
|
||||
{"text": "Contains signature", "passed": false},
|
||||
{"text": "Readable text", "passed": true}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If no expectations were provided, omit the `expectation_results` field entirely.
|
||||
|
||||
## Field Descriptions
|
||||
|
||||
- **winner**: "A", "B", or "TIE"
|
||||
- **reasoning**: Clear explanation of why the winner was chosen (or why it's a tie)
|
||||
- **rubric**: Structured rubric evaluation for each output
|
||||
- **content**: Scores for content criteria (correctness, completeness, accuracy)
|
||||
- **structure**: Scores for structure criteria (organization, formatting, usability)
|
||||
- **content_score**: Average of content criteria (1-5)
|
||||
- **structure_score**: Average of structure criteria (1-5)
|
||||
- **overall_score**: Combined score scaled to 1-10
|
||||
- **output_quality**: Summary quality assessment
|
||||
- **score**: 1-10 rating (should match rubric overall_score)
|
||||
- **strengths**: List of positive aspects
|
||||
- **weaknesses**: List of issues or shortcomings
|
||||
- **expectation_results**: (Only if expectations provided)
|
||||
- **passed**: Number of expectations that passed
|
||||
- **total**: Total number of expectations
|
||||
- **pass_rate**: Fraction passed (0.0 to 1.0)
|
||||
- **details**: Individual expectation results
|
||||
|
||||
## Guidelines
|
||||
|
||||
- **Stay blind**: DO NOT try to infer which skill produced which output. Judge purely on output quality.
|
||||
- **Be specific**: Cite specific examples when explaining strengths and weaknesses.
|
||||
- **Be decisive**: Choose a winner unless outputs are genuinely equivalent.
|
||||
- **Output quality first**: Assertion scores are secondary to overall task completion.
|
||||
- **Be objective**: Don't favor outputs based on style preferences; focus on correctness and completeness.
|
||||
- **Explain your reasoning**: The reasoning field should make it clear why you chose the winner.
|
||||
- **Handle edge cases**: If both outputs fail, pick the one that fails less badly. If both are excellent, pick the one that's marginally better.
|
||||
223
1-Vue3-Dev/.agents/skills/skill-creator/agents/grader.md
Normal file
223
1-Vue3-Dev/.agents/skills/skill-creator/agents/grader.md
Normal file
@@ -0,0 +1,223 @@
|
||||
# Grader Agent
|
||||
|
||||
Evaluate expectations against an execution transcript and outputs.
|
||||
|
||||
## Role
|
||||
|
||||
The Grader reviews a transcript and output files, then determines whether each expectation passes or fails. Provide clear evidence for each judgment.
|
||||
|
||||
You have two jobs: grade the outputs, and critique the evals themselves. A passing grade on a weak assertion is worse than useless — it creates false confidence. When you notice an assertion that's trivially satisfied, or an important outcome that no assertion checks, say so.
|
||||
|
||||
## Inputs
|
||||
|
||||
You receive these parameters in your prompt:
|
||||
|
||||
- **expectations**: List of expectations to evaluate (strings)
|
||||
- **transcript_path**: Path to the execution transcript (markdown file)
|
||||
- **outputs_dir**: Directory containing output files from execution
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Read the Transcript
|
||||
|
||||
1. Read the transcript file completely
|
||||
2. Note the eval prompt, execution steps, and final result
|
||||
3. Identify any issues or errors documented
|
||||
|
||||
### Step 2: Examine Output Files
|
||||
|
||||
1. List files in outputs_dir
|
||||
2. Read/examine each file relevant to the expectations. If outputs aren't plain text, use the inspection tools provided in your prompt — don't rely solely on what the transcript says the executor produced.
|
||||
3. Note contents, structure, and quality
|
||||
|
||||
### Step 3: Evaluate Each Assertion
|
||||
|
||||
For each expectation:
|
||||
|
||||
1. **Search for evidence** in the transcript and outputs
|
||||
2. **Determine verdict**:
|
||||
- **PASS**: Clear evidence the expectation is true AND the evidence reflects genuine task completion, not just surface-level compliance
|
||||
- **FAIL**: No evidence, or evidence contradicts the expectation, or the evidence is superficial (e.g., correct filename but empty/wrong content)
|
||||
3. **Cite the evidence**: Quote the specific text or describe what you found
|
||||
|
||||
### Step 4: Extract and Verify Claims
|
||||
|
||||
Beyond the predefined expectations, extract implicit claims from the outputs and verify them:
|
||||
|
||||
1. **Extract claims** from the transcript and outputs:
|
||||
- Factual statements ("The form has 12 fields")
|
||||
- Process claims ("Used pypdf to fill the form")
|
||||
- Quality claims ("All fields were filled correctly")
|
||||
|
||||
2. **Verify each claim**:
|
||||
- **Factual claims**: Can be checked against the outputs or external sources
|
||||
- **Process claims**: Can be verified from the transcript
|
||||
- **Quality claims**: Evaluate whether the claim is justified
|
||||
|
||||
3. **Flag unverifiable claims**: Note claims that cannot be verified with available information
|
||||
|
||||
This catches issues that predefined expectations might miss.
|
||||
|
||||
### Step 5: Read User Notes
|
||||
|
||||
If `{outputs_dir}/user_notes.md` exists:
|
||||
1. Read it and note any uncertainties or issues flagged by the executor
|
||||
2. Include relevant concerns in the grading output
|
||||
3. These may reveal problems even when expectations pass
|
||||
|
||||
### Step 6: Critique the Evals
|
||||
|
||||
After grading, consider whether the evals themselves could be improved. Only surface suggestions when there's a clear gap.
|
||||
|
||||
Good suggestions test meaningful outcomes — assertions that are hard to satisfy without actually doing the work correctly. Think about what makes an assertion *discriminating*: it passes when the skill genuinely succeeds and fails when it doesn't.
|
||||
|
||||
Suggestions worth raising:
|
||||
- An assertion that passed but would also pass for a clearly wrong output (e.g., checking filename existence but not file content)
|
||||
- An important outcome you observed — good or bad — that no assertion covers at all
|
||||
- An assertion that can't actually be verified from the available outputs
|
||||
|
||||
Keep the bar high. The goal is to flag things the eval author would say "good catch" about, not to nitpick every assertion.
|
||||
|
||||
### Step 7: Write Grading Results
|
||||
|
||||
Save results to `{outputs_dir}/../grading.json` (sibling to outputs_dir).
|
||||
|
||||
## Grading Criteria
|
||||
|
||||
**PASS when**:
|
||||
- The transcript or outputs clearly demonstrate the expectation is true
|
||||
- Specific evidence can be cited
|
||||
- The evidence reflects genuine substance, not just surface compliance (e.g., a file exists AND contains correct content, not just the right filename)
|
||||
|
||||
**FAIL when**:
|
||||
- No evidence found for the expectation
|
||||
- Evidence contradicts the expectation
|
||||
- The expectation cannot be verified from available information
|
||||
- The evidence is superficial — the assertion is technically satisfied but the underlying task outcome is wrong or incomplete
|
||||
- The output appears to meet the assertion by coincidence rather than by actually doing the work
|
||||
|
||||
**When uncertain**: The burden of proof to pass is on the expectation.
|
||||
|
||||
### Step 8: Read Executor Metrics and Timing
|
||||
|
||||
1. If `{outputs_dir}/metrics.json` exists, read it and include in grading output
|
||||
2. If `{outputs_dir}/../timing.json` exists, read it and include timing data
|
||||
|
||||
## Output Format
|
||||
|
||||
Write a JSON file with this structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"expectations": [
|
||||
{
|
||||
"text": "The output includes the name 'John Smith'",
|
||||
"passed": true,
|
||||
"evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'"
|
||||
},
|
||||
{
|
||||
"text": "The spreadsheet has a SUM formula in cell B10",
|
||||
"passed": false,
|
||||
"evidence": "No spreadsheet was created. The output was a text file."
|
||||
},
|
||||
{
|
||||
"text": "The assistant used the skill's OCR script",
|
||||
"passed": true,
|
||||
"evidence": "Transcript Step 2 shows: 'Tool: Bash - python ocr_script.py image.png'"
|
||||
}
|
||||
],
|
||||
"summary": {
|
||||
"passed": 2,
|
||||
"failed": 1,
|
||||
"total": 3,
|
||||
"pass_rate": 0.67
|
||||
},
|
||||
"execution_metrics": {
|
||||
"tool_calls": {
|
||||
"Read": 5,
|
||||
"Write": 2,
|
||||
"Bash": 8
|
||||
},
|
||||
"total_tool_calls": 15,
|
||||
"total_steps": 6,
|
||||
"errors_encountered": 0,
|
||||
"output_chars": 12450,
|
||||
"transcript_chars": 3200
|
||||
},
|
||||
"timing": {
|
||||
"executor_duration_seconds": 165.0,
|
||||
"grader_duration_seconds": 26.0,
|
||||
"total_duration_seconds": 191.0
|
||||
},
|
||||
"claims": [
|
||||
{
|
||||
"claim": "The form has 12 fillable fields",
|
||||
"type": "factual",
|
||||
"verified": true,
|
||||
"evidence": "Counted 12 fields in field_info.json"
|
||||
},
|
||||
{
|
||||
"claim": "All required fields were populated",
|
||||
"type": "quality",
|
||||
"verified": false,
|
||||
"evidence": "Reference section was left blank despite data being available"
|
||||
}
|
||||
],
|
||||
"user_notes_summary": {
|
||||
"uncertainties": ["Used 2023 data, may be stale"],
|
||||
"needs_review": [],
|
||||
"workarounds": ["Fell back to text overlay for non-fillable fields"]
|
||||
},
|
||||
"eval_feedback": {
|
||||
"suggestions": [
|
||||
{
|
||||
"assertion": "The output includes the name 'John Smith'",
|
||||
"reason": "A hallucinated document that mentions the name would also pass — consider checking it appears as the primary contact with matching phone and email from the input"
|
||||
},
|
||||
{
|
||||
"reason": "No assertion checks whether the extracted phone numbers match the input — I observed incorrect numbers in the output that went uncaught"
|
||||
}
|
||||
],
|
||||
"overall": "Assertions check presence but not correctness. Consider adding content verification."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Field Descriptions
|
||||
|
||||
- **expectations**: Array of graded expectations
|
||||
- **text**: The original expectation text
|
||||
- **passed**: Boolean - true if expectation passes
|
||||
- **evidence**: Specific quote or description supporting the verdict
|
||||
- **summary**: Aggregate statistics
|
||||
- **passed**: Count of passed expectations
|
||||
- **failed**: Count of failed expectations
|
||||
- **total**: Total expectations evaluated
|
||||
- **pass_rate**: Fraction passed (0.0 to 1.0)
|
||||
- **execution_metrics**: Copied from executor's metrics.json (if available)
|
||||
- **output_chars**: Total character count of output files (proxy for tokens)
|
||||
- **transcript_chars**: Character count of transcript
|
||||
- **timing**: Wall clock timing from timing.json (if available)
|
||||
- **executor_duration_seconds**: Time spent in executor subagent
|
||||
- **total_duration_seconds**: Total elapsed time for the run
|
||||
- **claims**: Extracted and verified claims from the output
|
||||
- **claim**: The statement being verified
|
||||
- **type**: "factual", "process", or "quality"
|
||||
- **verified**: Boolean - whether the claim holds
|
||||
- **evidence**: Supporting or contradicting evidence
|
||||
- **user_notes_summary**: Issues flagged by the executor
|
||||
- **uncertainties**: Things the executor wasn't sure about
|
||||
- **needs_review**: Items requiring human attention
|
||||
- **workarounds**: Places where the skill didn't work as expected
|
||||
- **eval_feedback**: Improvement suggestions for the evals (only when warranted)
|
||||
- **suggestions**: List of concrete suggestions, each with a `reason` and optionally an `assertion` it relates to
|
||||
- **overall**: Brief assessment — can be "No suggestions, evals look solid" if nothing to flag
|
||||
|
||||
## Guidelines
|
||||
|
||||
- **Be objective**: Base verdicts on evidence, not assumptions
|
||||
- **Be specific**: Quote the exact text that supports your verdict
|
||||
- **Be thorough**: Check both transcript and output files
|
||||
- **Be consistent**: Apply the same standard to each expectation
|
||||
- **Explain failures**: Make it clear why evidence was insufficient
|
||||
- **No partial credit**: Each expectation is pass or fail, not partial
|
||||
146
1-Vue3-Dev/.agents/skills/skill-creator/assets/eval_review.html
Normal file
146
1-Vue3-Dev/.agents/skills/skill-creator/assets/eval_review.html
Normal file
@@ -0,0 +1,146 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Eval Set Review - __SKILL_NAME_PLACEHOLDER__</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Lora', Georgia, serif; background: #faf9f5; padding: 2rem; color: #141413; }
|
||||
h1 { font-family: 'Poppins', sans-serif; margin-bottom: 0.5rem; font-size: 1.5rem; }
|
||||
.description { color: #b0aea5; margin-bottom: 1.5rem; font-style: italic; max-width: 900px; }
|
||||
.controls { margin-bottom: 1rem; display: flex; gap: 0.5rem; }
|
||||
.btn { font-family: 'Poppins', sans-serif; padding: 0.5rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.875rem; font-weight: 500; }
|
||||
.btn-add { background: #6a9bcc; color: white; }
|
||||
.btn-add:hover { background: #5889b8; }
|
||||
.btn-export { background: #d97757; color: white; }
|
||||
.btn-export:hover { background: #c4613f; }
|
||||
table { width: 100%; max-width: 1100px; border-collapse: collapse; background: white; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
|
||||
th { font-family: 'Poppins', sans-serif; background: #141413; color: #faf9f5; padding: 0.75rem 1rem; text-align: left; font-size: 0.875rem; }
|
||||
td { padding: 0.75rem 1rem; border-bottom: 1px solid #e8e6dc; vertical-align: top; }
|
||||
tr:nth-child(even) td { background: #faf9f5; }
|
||||
tr:hover td { background: #f3f1ea; }
|
||||
.section-header td { background: #e8e6dc; font-family: 'Poppins', sans-serif; font-weight: 500; font-size: 0.8rem; color: #141413; text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
.query-input { width: 100%; padding: 0.4rem; border: 1px solid #e8e6dc; border-radius: 4px; font-size: 0.875rem; font-family: 'Lora', Georgia, serif; resize: vertical; min-height: 60px; }
|
||||
.query-input:focus { outline: none; border-color: #d97757; box-shadow: 0 0 0 2px rgba(217,119,87,0.15); }
|
||||
.toggle { position: relative; display: inline-block; width: 44px; height: 24px; }
|
||||
.toggle input { opacity: 0; width: 0; height: 0; }
|
||||
.toggle .slider { position: absolute; inset: 0; background: #b0aea5; border-radius: 24px; cursor: pointer; transition: 0.2s; }
|
||||
.toggle .slider::before { content: ""; position: absolute; width: 18px; height: 18px; left: 3px; bottom: 3px; background: white; border-radius: 50%; transition: 0.2s; }
|
||||
.toggle input:checked + .slider { background: #d97757; }
|
||||
.toggle input:checked + .slider::before { transform: translateX(20px); }
|
||||
.btn-delete { background: #c44; color: white; padding: 0.3rem 0.6rem; border: none; border-radius: 4px; cursor: pointer; font-size: 0.75rem; font-family: 'Poppins', sans-serif; }
|
||||
.btn-delete:hover { background: #a33; }
|
||||
.summary { margin-top: 1rem; color: #b0aea5; font-size: 0.875rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Eval Set Review: <span id="skill-name">__SKILL_NAME_PLACEHOLDER__</span></h1>
|
||||
<p class="description">Current description: <span id="skill-desc">__SKILL_DESCRIPTION_PLACEHOLDER__</span></p>
|
||||
|
||||
<div class="controls">
|
||||
<button class="btn btn-add" onclick="addRow()">+ Add Query</button>
|
||||
<button class="btn btn-export" onclick="exportEvalSet()">Export Eval Set</button>
|
||||
</div>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:65%">Query</th>
|
||||
<th style="width:18%">Should Trigger</th>
|
||||
<th style="width:10%">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="eval-body"></tbody>
|
||||
</table>
|
||||
|
||||
<p class="summary" id="summary"></p>
|
||||
|
||||
<script>
|
||||
const EVAL_DATA = __EVAL_DATA_PLACEHOLDER__;
|
||||
|
||||
let evalItems = [...EVAL_DATA];
|
||||
|
||||
function render() {
|
||||
const tbody = document.getElementById('eval-body');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
// Sort: should-trigger first, then should-not-trigger
|
||||
const sorted = evalItems
|
||||
.map((item, origIdx) => ({ ...item, origIdx }))
|
||||
.sort((a, b) => (b.should_trigger ? 1 : 0) - (a.should_trigger ? 1 : 0));
|
||||
|
||||
let lastGroup = null;
|
||||
sorted.forEach(item => {
|
||||
const group = item.should_trigger ? 'trigger' : 'no-trigger';
|
||||
if (group !== lastGroup) {
|
||||
const headerRow = document.createElement('tr');
|
||||
headerRow.className = 'section-header';
|
||||
headerRow.innerHTML = `<td colspan="3">${item.should_trigger ? 'Should Trigger' : 'Should NOT Trigger'}</td>`;
|
||||
tbody.appendChild(headerRow);
|
||||
lastGroup = group;
|
||||
}
|
||||
|
||||
const idx = item.origIdx;
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = `
|
||||
<td><textarea class="query-input" onchange="updateQuery(${idx}, this.value)">${escapeHtml(item.query)}</textarea></td>
|
||||
<td>
|
||||
<label class="toggle">
|
||||
<input type="checkbox" ${item.should_trigger ? 'checked' : ''} onchange="updateTrigger(${idx}, this.checked)">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<span style="margin-left:8px;font-size:0.8rem;color:#b0aea5">${item.should_trigger ? 'Yes' : 'No'}</span>
|
||||
</td>
|
||||
<td><button class="btn-delete" onclick="deleteRow(${idx})">Delete</button></td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
updateSummary();
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function updateQuery(idx, value) { evalItems[idx].query = value; updateSummary(); }
|
||||
function updateTrigger(idx, value) { evalItems[idx].should_trigger = value; render(); }
|
||||
function deleteRow(idx) { evalItems.splice(idx, 1); render(); }
|
||||
|
||||
function addRow() {
|
||||
evalItems.push({ query: '', should_trigger: true });
|
||||
render();
|
||||
const inputs = document.querySelectorAll('.query-input');
|
||||
inputs[inputs.length - 1].focus();
|
||||
}
|
||||
|
||||
function updateSummary() {
|
||||
const trigger = evalItems.filter(i => i.should_trigger).length;
|
||||
const noTrigger = evalItems.filter(i => !i.should_trigger).length;
|
||||
document.getElementById('summary').textContent =
|
||||
`${evalItems.length} queries total: ${trigger} should trigger, ${noTrigger} should not trigger`;
|
||||
}
|
||||
|
||||
function exportEvalSet() {
|
||||
const valid = evalItems.filter(i => i.query.trim() !== '');
|
||||
const data = valid.map(i => ({ query: i.query.trim(), should_trigger: i.should_trigger }));
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'eval_set.json';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,471 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate and serve a review page for eval results.
|
||||
|
||||
Reads the workspace directory, discovers runs (directories with outputs/),
|
||||
embeds all output data into a self-contained HTML page, and serves it via
|
||||
a tiny HTTP server. Feedback auto-saves to feedback.json in the workspace.
|
||||
|
||||
Usage:
|
||||
python generate_review.py <workspace-path> [--port PORT] [--skill-name NAME]
|
||||
python generate_review.py <workspace-path> --previous-feedback /path/to/old/feedback.json
|
||||
|
||||
No dependencies beyond the Python stdlib are required.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import webbrowser
|
||||
from functools import partial
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
# Files to exclude from output listings
|
||||
METADATA_FILES = {"transcript.md", "user_notes.md", "metrics.json"}
|
||||
|
||||
# Extensions we render as inline text
|
||||
TEXT_EXTENSIONS = {
|
||||
".txt", ".md", ".json", ".csv", ".py", ".js", ".ts", ".tsx", ".jsx",
|
||||
".yaml", ".yml", ".xml", ".html", ".css", ".sh", ".rb", ".go", ".rs",
|
||||
".java", ".c", ".cpp", ".h", ".hpp", ".sql", ".r", ".toml",
|
||||
}
|
||||
|
||||
# Extensions we render as inline images
|
||||
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"}
|
||||
|
||||
# MIME type overrides for common types
|
||||
MIME_OVERRIDES = {
|
||||
".svg": "image/svg+xml",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
}
|
||||
|
||||
|
||||
def get_mime_type(path: Path) -> str:
|
||||
ext = path.suffix.lower()
|
||||
if ext in MIME_OVERRIDES:
|
||||
return MIME_OVERRIDES[ext]
|
||||
mime, _ = mimetypes.guess_type(str(path))
|
||||
return mime or "application/octet-stream"
|
||||
|
||||
|
||||
def find_runs(workspace: Path) -> list[dict]:
|
||||
"""Recursively find directories that contain an outputs/ subdirectory."""
|
||||
runs: list[dict] = []
|
||||
_find_runs_recursive(workspace, workspace, runs)
|
||||
runs.sort(key=lambda r: (r.get("eval_id", float("inf")), r["id"]))
|
||||
return runs
|
||||
|
||||
|
||||
def _find_runs_recursive(root: Path, current: Path, runs: list[dict]) -> None:
|
||||
if not current.is_dir():
|
||||
return
|
||||
|
||||
outputs_dir = current / "outputs"
|
||||
if outputs_dir.is_dir():
|
||||
run = build_run(root, current)
|
||||
if run:
|
||||
runs.append(run)
|
||||
return
|
||||
|
||||
skip = {"node_modules", ".git", "__pycache__", "skill", "inputs"}
|
||||
for child in sorted(current.iterdir()):
|
||||
if child.is_dir() and child.name not in skip:
|
||||
_find_runs_recursive(root, child, runs)
|
||||
|
||||
|
||||
def build_run(root: Path, run_dir: Path) -> dict | None:
|
||||
"""Build a run dict with prompt, outputs, and grading data."""
|
||||
prompt = ""
|
||||
eval_id = None
|
||||
|
||||
# Try eval_metadata.json
|
||||
for candidate in [run_dir / "eval_metadata.json", run_dir.parent / "eval_metadata.json"]:
|
||||
if candidate.exists():
|
||||
try:
|
||||
metadata = json.loads(candidate.read_text())
|
||||
prompt = metadata.get("prompt", "")
|
||||
eval_id = metadata.get("eval_id")
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
if prompt:
|
||||
break
|
||||
|
||||
# Fall back to transcript.md
|
||||
if not prompt:
|
||||
for candidate in [run_dir / "transcript.md", run_dir / "outputs" / "transcript.md"]:
|
||||
if candidate.exists():
|
||||
try:
|
||||
text = candidate.read_text()
|
||||
match = re.search(r"## Eval Prompt\n\n([\s\S]*?)(?=\n##|$)", text)
|
||||
if match:
|
||||
prompt = match.group(1).strip()
|
||||
except OSError:
|
||||
pass
|
||||
if prompt:
|
||||
break
|
||||
|
||||
if not prompt:
|
||||
prompt = "(No prompt found)"
|
||||
|
||||
run_id = str(run_dir.relative_to(root)).replace("/", "-").replace("\\", "-")
|
||||
|
||||
# Collect output files
|
||||
outputs_dir = run_dir / "outputs"
|
||||
output_files: list[dict] = []
|
||||
if outputs_dir.is_dir():
|
||||
for f in sorted(outputs_dir.iterdir()):
|
||||
if f.is_file() and f.name not in METADATA_FILES:
|
||||
output_files.append(embed_file(f))
|
||||
|
||||
# Load grading if present
|
||||
grading = None
|
||||
for candidate in [run_dir / "grading.json", run_dir.parent / "grading.json"]:
|
||||
if candidate.exists():
|
||||
try:
|
||||
grading = json.loads(candidate.read_text())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
if grading:
|
||||
break
|
||||
|
||||
return {
|
||||
"id": run_id,
|
||||
"prompt": prompt,
|
||||
"eval_id": eval_id,
|
||||
"outputs": output_files,
|
||||
"grading": grading,
|
||||
}
|
||||
|
||||
|
||||
def embed_file(path: Path) -> dict:
|
||||
"""Read a file and return an embedded representation."""
|
||||
ext = path.suffix.lower()
|
||||
mime = get_mime_type(path)
|
||||
|
||||
if ext in TEXT_EXTENSIONS:
|
||||
try:
|
||||
content = path.read_text(errors="replace")
|
||||
except OSError:
|
||||
content = "(Error reading file)"
|
||||
return {
|
||||
"name": path.name,
|
||||
"type": "text",
|
||||
"content": content,
|
||||
}
|
||||
elif ext in IMAGE_EXTENSIONS:
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
except OSError:
|
||||
return {"name": path.name, "type": "error", "content": "(Error reading file)"}
|
||||
return {
|
||||
"name": path.name,
|
||||
"type": "image",
|
||||
"mime": mime,
|
||||
"data_uri": f"data:{mime};base64,{b64}",
|
||||
}
|
||||
elif ext == ".pdf":
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
except OSError:
|
||||
return {"name": path.name, "type": "error", "content": "(Error reading file)"}
|
||||
return {
|
||||
"name": path.name,
|
||||
"type": "pdf",
|
||||
"data_uri": f"data:{mime};base64,{b64}",
|
||||
}
|
||||
elif ext == ".xlsx":
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
except OSError:
|
||||
return {"name": path.name, "type": "error", "content": "(Error reading file)"}
|
||||
return {
|
||||
"name": path.name,
|
||||
"type": "xlsx",
|
||||
"data_b64": b64,
|
||||
}
|
||||
else:
|
||||
# Binary / unknown — base64 download link
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
except OSError:
|
||||
return {"name": path.name, "type": "error", "content": "(Error reading file)"}
|
||||
return {
|
||||
"name": path.name,
|
||||
"type": "binary",
|
||||
"mime": mime,
|
||||
"data_uri": f"data:{mime};base64,{b64}",
|
||||
}
|
||||
|
||||
|
||||
def load_previous_iteration(workspace: Path) -> dict[str, dict]:
|
||||
"""Load previous iteration's feedback and outputs.
|
||||
|
||||
Returns a map of run_id -> {"feedback": str, "outputs": list[dict]}.
|
||||
"""
|
||||
result: dict[str, dict] = {}
|
||||
|
||||
# Load feedback
|
||||
feedback_map: dict[str, str] = {}
|
||||
feedback_path = workspace / "feedback.json"
|
||||
if feedback_path.exists():
|
||||
try:
|
||||
data = json.loads(feedback_path.read_text())
|
||||
feedback_map = {
|
||||
r["run_id"]: r["feedback"]
|
||||
for r in data.get("reviews", [])
|
||||
if r.get("feedback", "").strip()
|
||||
}
|
||||
except (json.JSONDecodeError, OSError, KeyError):
|
||||
pass
|
||||
|
||||
# Load runs (to get outputs)
|
||||
prev_runs = find_runs(workspace)
|
||||
for run in prev_runs:
|
||||
result[run["id"]] = {
|
||||
"feedback": feedback_map.get(run["id"], ""),
|
||||
"outputs": run.get("outputs", []),
|
||||
}
|
||||
|
||||
# Also add feedback for run_ids that had feedback but no matching run
|
||||
for run_id, fb in feedback_map.items():
|
||||
if run_id not in result:
|
||||
result[run_id] = {"feedback": fb, "outputs": []}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def generate_html(
|
||||
runs: list[dict],
|
||||
skill_name: str,
|
||||
previous: dict[str, dict] | None = None,
|
||||
benchmark: dict | None = None,
|
||||
) -> str:
|
||||
"""Generate the complete standalone HTML page with embedded data."""
|
||||
template_path = Path(__file__).parent / "viewer.html"
|
||||
template = template_path.read_text()
|
||||
|
||||
# Build previous_feedback and previous_outputs maps for the template
|
||||
previous_feedback: dict[str, str] = {}
|
||||
previous_outputs: dict[str, list[dict]] = {}
|
||||
if previous:
|
||||
for run_id, data in previous.items():
|
||||
if data.get("feedback"):
|
||||
previous_feedback[run_id] = data["feedback"]
|
||||
if data.get("outputs"):
|
||||
previous_outputs[run_id] = data["outputs"]
|
||||
|
||||
embedded = {
|
||||
"skill_name": skill_name,
|
||||
"runs": runs,
|
||||
"previous_feedback": previous_feedback,
|
||||
"previous_outputs": previous_outputs,
|
||||
}
|
||||
if benchmark:
|
||||
embedded["benchmark"] = benchmark
|
||||
|
||||
data_json = json.dumps(embedded)
|
||||
|
||||
return template.replace("/*__EMBEDDED_DATA__*/", f"const EMBEDDED_DATA = {data_json};")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP server (stdlib only, zero dependencies)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _kill_port(port: int) -> None:
|
||||
"""Kill any process listening on the given port."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["lsof", "-ti", f":{port}"],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
for pid_str in result.stdout.strip().split("\n"):
|
||||
if pid_str.strip():
|
||||
try:
|
||||
os.kill(int(pid_str.strip()), signal.SIGTERM)
|
||||
except (ProcessLookupError, ValueError):
|
||||
pass
|
||||
if result.stdout.strip():
|
||||
time.sleep(0.5)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
except FileNotFoundError:
|
||||
print("Note: lsof not found, cannot check if port is in use", file=sys.stderr)
|
||||
|
||||
class ReviewHandler(BaseHTTPRequestHandler):
|
||||
"""Serves the review HTML and handles feedback saves.
|
||||
|
||||
Regenerates the HTML on each page load so that refreshing the browser
|
||||
picks up new eval outputs without restarting the server.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
workspace: Path,
|
||||
skill_name: str,
|
||||
feedback_path: Path,
|
||||
previous: dict[str, dict],
|
||||
benchmark_path: Path | None,
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
self.workspace = workspace
|
||||
self.skill_name = skill_name
|
||||
self.feedback_path = feedback_path
|
||||
self.previous = previous
|
||||
self.benchmark_path = benchmark_path
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
if self.path == "/" or self.path == "/index.html":
|
||||
# Regenerate HTML on each request (re-scans workspace for new outputs)
|
||||
runs = find_runs(self.workspace)
|
||||
benchmark = None
|
||||
if self.benchmark_path and self.benchmark_path.exists():
|
||||
try:
|
||||
benchmark = json.loads(self.benchmark_path.read_text())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
html = generate_html(runs, self.skill_name, self.previous, benchmark)
|
||||
content = html.encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
elif self.path == "/api/feedback":
|
||||
data = b"{}"
|
||||
if self.feedback_path.exists():
|
||||
data = self.feedback_path.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
else:
|
||||
self.send_error(404)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
if self.path == "/api/feedback":
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(length)
|
||||
try:
|
||||
data = json.loads(body)
|
||||
if not isinstance(data, dict) or "reviews" not in data:
|
||||
raise ValueError("Expected JSON object with 'reviews' key")
|
||||
self.feedback_path.write_text(json.dumps(data, indent=2) + "\n")
|
||||
resp = b'{"ok":true}'
|
||||
self.send_response(200)
|
||||
except (json.JSONDecodeError, OSError, ValueError) as e:
|
||||
resp = json.dumps({"error": str(e)}).encode()
|
||||
self.send_response(500)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(resp)))
|
||||
self.end_headers()
|
||||
self.wfile.write(resp)
|
||||
else:
|
||||
self.send_error(404)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
# Suppress request logging to keep terminal clean
|
||||
pass
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Generate and serve eval review")
|
||||
parser.add_argument("workspace", type=Path, help="Path to workspace directory")
|
||||
parser.add_argument("--port", "-p", type=int, default=3117, help="Server port (default: 3117)")
|
||||
parser.add_argument("--skill-name", "-n", type=str, default=None, help="Skill name for header")
|
||||
parser.add_argument(
|
||||
"--previous-workspace", type=Path, default=None,
|
||||
help="Path to previous iteration's workspace (shows old outputs and feedback as context)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--benchmark", type=Path, default=None,
|
||||
help="Path to benchmark.json to show in the Benchmark tab",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--static", "-s", type=Path, default=None,
|
||||
help="Write standalone HTML to this path instead of starting a server",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
workspace = args.workspace.resolve()
|
||||
if not workspace.is_dir():
|
||||
print(f"Error: {workspace} is not a directory", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
runs = find_runs(workspace)
|
||||
if not runs:
|
||||
print(f"No runs found in {workspace}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_name = args.skill_name or workspace.name.replace("-workspace", "")
|
||||
feedback_path = workspace / "feedback.json"
|
||||
|
||||
previous: dict[str, dict] = {}
|
||||
if args.previous_workspace:
|
||||
previous = load_previous_iteration(args.previous_workspace.resolve())
|
||||
|
||||
benchmark_path = args.benchmark.resolve() if args.benchmark else None
|
||||
benchmark = None
|
||||
if benchmark_path and benchmark_path.exists():
|
||||
try:
|
||||
benchmark = json.loads(benchmark_path.read_text())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
|
||||
if args.static:
|
||||
html = generate_html(runs, skill_name, previous, benchmark)
|
||||
args.static.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.static.write_text(html)
|
||||
print(f"\n Static viewer written to: {args.static}\n")
|
||||
sys.exit(0)
|
||||
|
||||
# Kill any existing process on the target port
|
||||
port = args.port
|
||||
_kill_port(port)
|
||||
handler = partial(ReviewHandler, workspace, skill_name, feedback_path, previous, benchmark_path)
|
||||
try:
|
||||
server = HTTPServer(("127.0.0.1", port), handler)
|
||||
except OSError:
|
||||
# Port still in use after kill attempt — find a free one
|
||||
server = HTTPServer(("127.0.0.1", 0), handler)
|
||||
port = server.server_address[1]
|
||||
|
||||
url = f"http://localhost:{port}"
|
||||
print(f"\n Eval Viewer")
|
||||
print(f" ─────────────────────────────────")
|
||||
print(f" URL: {url}")
|
||||
print(f" Workspace: {workspace}")
|
||||
print(f" Feedback: {feedback_path}")
|
||||
if previous:
|
||||
print(f" Previous: {args.previous_workspace} ({len(previous)} runs)")
|
||||
if benchmark_path:
|
||||
print(f" Benchmark: {benchmark_path}")
|
||||
print(f"\n Press Ctrl+C to stop.\n")
|
||||
|
||||
webbrowser.open(url)
|
||||
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\nStopped.")
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
1325
1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/viewer.html
Normal file
1325
1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/viewer.html
Normal file
File diff suppressed because it is too large
Load Diff
430
1-Vue3-Dev/.agents/skills/skill-creator/references/schemas.md
Normal file
430
1-Vue3-Dev/.agents/skills/skill-creator/references/schemas.md
Normal file
@@ -0,0 +1,430 @@
|
||||
# JSON Schemas
|
||||
|
||||
This document defines the JSON schemas used by skill-creator.
|
||||
|
||||
---
|
||||
|
||||
## evals.json
|
||||
|
||||
Defines the evals for a skill. Located at `evals/evals.json` within the skill directory.
|
||||
|
||||
```json
|
||||
{
|
||||
"skill_name": "example-skill",
|
||||
"evals": [
|
||||
{
|
||||
"id": 1,
|
||||
"prompt": "User's example prompt",
|
||||
"expected_output": "Description of expected result",
|
||||
"files": ["evals/files/sample1.pdf"],
|
||||
"expectations": [
|
||||
"The output includes X",
|
||||
"The skill used script Y"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Fields:**
|
||||
- `skill_name`: Name matching the skill's frontmatter
|
||||
- `evals[].id`: Unique integer identifier
|
||||
- `evals[].prompt`: The task to execute
|
||||
- `evals[].expected_output`: Human-readable description of success
|
||||
- `evals[].files`: Optional list of input file paths (relative to skill root)
|
||||
- `evals[].expectations`: List of verifiable statements
|
||||
|
||||
---
|
||||
|
||||
## history.json
|
||||
|
||||
Tracks version progression in Improve mode. Located at workspace root.
|
||||
|
||||
```json
|
||||
{
|
||||
"started_at": "2026-01-15T10:30:00Z",
|
||||
"skill_name": "pdf",
|
||||
"current_best": "v2",
|
||||
"iterations": [
|
||||
{
|
||||
"version": "v0",
|
||||
"parent": null,
|
||||
"expectation_pass_rate": 0.65,
|
||||
"grading_result": "baseline",
|
||||
"is_current_best": false
|
||||
},
|
||||
{
|
||||
"version": "v1",
|
||||
"parent": "v0",
|
||||
"expectation_pass_rate": 0.75,
|
||||
"grading_result": "won",
|
||||
"is_current_best": false
|
||||
},
|
||||
{
|
||||
"version": "v2",
|
||||
"parent": "v1",
|
||||
"expectation_pass_rate": 0.85,
|
||||
"grading_result": "won",
|
||||
"is_current_best": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Fields:**
|
||||
- `started_at`: ISO timestamp of when improvement started
|
||||
- `skill_name`: Name of the skill being improved
|
||||
- `current_best`: Version identifier of the best performer
|
||||
- `iterations[].version`: Version identifier (v0, v1, ...)
|
||||
- `iterations[].parent`: Parent version this was derived from
|
||||
- `iterations[].expectation_pass_rate`: Pass rate from grading
|
||||
- `iterations[].grading_result`: "baseline", "won", "lost", or "tie"
|
||||
- `iterations[].is_current_best`: Whether this is the current best version
|
||||
|
||||
---
|
||||
|
||||
## grading.json
|
||||
|
||||
Output from the grader agent. Located at `<run-dir>/grading.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"expectations": [
|
||||
{
|
||||
"text": "The output includes the name 'John Smith'",
|
||||
"passed": true,
|
||||
"evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'"
|
||||
},
|
||||
{
|
||||
"text": "The spreadsheet has a SUM formula in cell B10",
|
||||
"passed": false,
|
||||
"evidence": "No spreadsheet was created. The output was a text file."
|
||||
}
|
||||
],
|
||||
"summary": {
|
||||
"passed": 2,
|
||||
"failed": 1,
|
||||
"total": 3,
|
||||
"pass_rate": 0.67
|
||||
},
|
||||
"execution_metrics": {
|
||||
"tool_calls": {
|
||||
"Read": 5,
|
||||
"Write": 2,
|
||||
"Bash": 8
|
||||
},
|
||||
"total_tool_calls": 15,
|
||||
"total_steps": 6,
|
||||
"errors_encountered": 0,
|
||||
"output_chars": 12450,
|
||||
"transcript_chars": 3200
|
||||
},
|
||||
"timing": {
|
||||
"executor_duration_seconds": 165.0,
|
||||
"grader_duration_seconds": 26.0,
|
||||
"total_duration_seconds": 191.0
|
||||
},
|
||||
"claims": [
|
||||
{
|
||||
"claim": "The form has 12 fillable fields",
|
||||
"type": "factual",
|
||||
"verified": true,
|
||||
"evidence": "Counted 12 fields in field_info.json"
|
||||
}
|
||||
],
|
||||
"user_notes_summary": {
|
||||
"uncertainties": ["Used 2023 data, may be stale"],
|
||||
"needs_review": [],
|
||||
"workarounds": ["Fell back to text overlay for non-fillable fields"]
|
||||
},
|
||||
"eval_feedback": {
|
||||
"suggestions": [
|
||||
{
|
||||
"assertion": "The output includes the name 'John Smith'",
|
||||
"reason": "A hallucinated document that mentions the name would also pass"
|
||||
}
|
||||
],
|
||||
"overall": "Assertions check presence but not correctness."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fields:**
|
||||
- `expectations[]`: Graded expectations with evidence
|
||||
- `summary`: Aggregate pass/fail counts
|
||||
- `execution_metrics`: Tool usage and output size (from executor's metrics.json)
|
||||
- `timing`: Wall clock timing (from timing.json)
|
||||
- `claims`: Extracted and verified claims from the output
|
||||
- `user_notes_summary`: Issues flagged by the executor
|
||||
- `eval_feedback`: (optional) Improvement suggestions for the evals, only present when the grader identifies issues worth raising
|
||||
|
||||
---
|
||||
|
||||
## metrics.json
|
||||
|
||||
Output from the executor agent. Located at `<run-dir>/outputs/metrics.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"tool_calls": {
|
||||
"Read": 5,
|
||||
"Write": 2,
|
||||
"Bash": 8,
|
||||
"Edit": 1,
|
||||
"Glob": 2,
|
||||
"Grep": 0
|
||||
},
|
||||
"total_tool_calls": 18,
|
||||
"total_steps": 6,
|
||||
"files_created": ["filled_form.pdf", "field_values.json"],
|
||||
"errors_encountered": 0,
|
||||
"output_chars": 12450,
|
||||
"transcript_chars": 3200
|
||||
}
|
||||
```
|
||||
|
||||
**Fields:**
|
||||
- `tool_calls`: Count per tool type
|
||||
- `total_tool_calls`: Sum of all tool calls
|
||||
- `total_steps`: Number of major execution steps
|
||||
- `files_created`: List of output files created
|
||||
- `errors_encountered`: Number of errors during execution
|
||||
- `output_chars`: Total character count of output files
|
||||
- `transcript_chars`: Character count of transcript
|
||||
|
||||
---
|
||||
|
||||
## timing.json
|
||||
|
||||
Wall clock timing for a run. Located at `<run-dir>/timing.json`.
|
||||
|
||||
**How to capture:** When a subagent task completes, the task notification includes `total_tokens` and `duration_ms`. Save these immediately — they are not persisted anywhere else and cannot be recovered after the fact.
|
||||
|
||||
```json
|
||||
{
|
||||
"total_tokens": 84852,
|
||||
"duration_ms": 23332,
|
||||
"total_duration_seconds": 23.3,
|
||||
"executor_start": "2026-01-15T10:30:00Z",
|
||||
"executor_end": "2026-01-15T10:32:45Z",
|
||||
"executor_duration_seconds": 165.0,
|
||||
"grader_start": "2026-01-15T10:32:46Z",
|
||||
"grader_end": "2026-01-15T10:33:12Z",
|
||||
"grader_duration_seconds": 26.0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## benchmark.json
|
||||
|
||||
Output from Benchmark mode. Located at `benchmarks/<timestamp>/benchmark.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"metadata": {
|
||||
"skill_name": "pdf",
|
||||
"skill_path": "/path/to/pdf",
|
||||
"executor_model": "claude-sonnet-4-20250514",
|
||||
"analyzer_model": "most-capable-model",
|
||||
"timestamp": "2026-01-15T10:30:00Z",
|
||||
"evals_run": [1, 2, 3],
|
||||
"runs_per_configuration": 3
|
||||
},
|
||||
|
||||
"runs": [
|
||||
{
|
||||
"eval_id": 1,
|
||||
"eval_name": "Ocean",
|
||||
"configuration": "with_skill",
|
||||
"run_number": 1,
|
||||
"result": {
|
||||
"pass_rate": 0.85,
|
||||
"passed": 6,
|
||||
"failed": 1,
|
||||
"total": 7,
|
||||
"time_seconds": 42.5,
|
||||
"tokens": 3800,
|
||||
"tool_calls": 18,
|
||||
"errors": 0
|
||||
},
|
||||
"expectations": [
|
||||
{"text": "...", "passed": true, "evidence": "..."}
|
||||
],
|
||||
"notes": [
|
||||
"Used 2023 data, may be stale",
|
||||
"Fell back to text overlay for non-fillable fields"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
"run_summary": {
|
||||
"with_skill": {
|
||||
"pass_rate": {"mean": 0.85, "stddev": 0.05, "min": 0.80, "max": 0.90},
|
||||
"time_seconds": {"mean": 45.0, "stddev": 12.0, "min": 32.0, "max": 58.0},
|
||||
"tokens": {"mean": 3800, "stddev": 400, "min": 3200, "max": 4100}
|
||||
},
|
||||
"without_skill": {
|
||||
"pass_rate": {"mean": 0.35, "stddev": 0.08, "min": 0.28, "max": 0.45},
|
||||
"time_seconds": {"mean": 32.0, "stddev": 8.0, "min": 24.0, "max": 42.0},
|
||||
"tokens": {"mean": 2100, "stddev": 300, "min": 1800, "max": 2500}
|
||||
},
|
||||
"delta": {
|
||||
"pass_rate": "+0.50",
|
||||
"time_seconds": "+13.0",
|
||||
"tokens": "+1700"
|
||||
}
|
||||
},
|
||||
|
||||
"notes": [
|
||||
"Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value",
|
||||
"Eval 3 shows high variance (50% ± 40%) - may be flaky or model-dependent",
|
||||
"Without-skill runs consistently fail on table extraction expectations",
|
||||
"Skill adds 13s average execution time but improves pass rate by 50%"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Fields:**
|
||||
- `metadata`: Information about the benchmark run
|
||||
- `skill_name`: Name of the skill
|
||||
- `timestamp`: When the benchmark was run
|
||||
- `evals_run`: List of eval names or IDs
|
||||
- `runs_per_configuration`: Number of runs per config (e.g. 3)
|
||||
- `runs[]`: Individual run results
|
||||
- `eval_id`: Numeric eval identifier
|
||||
- `eval_name`: Human-readable eval name (used as section header in the viewer)
|
||||
- `configuration`: Must be `"with_skill"` or `"without_skill"` (the viewer uses this exact string for grouping and color coding)
|
||||
- `run_number`: Integer run number (1, 2, 3...)
|
||||
- `result`: Nested object with `pass_rate`, `passed`, `total`, `time_seconds`, `tokens`, `errors`
|
||||
- `run_summary`: Statistical aggregates per configuration
|
||||
- `with_skill` / `without_skill`: Each contains `pass_rate`, `time_seconds`, `tokens` objects with `mean` and `stddev` fields
|
||||
- `delta`: Difference strings like `"+0.50"`, `"+13.0"`, `"+1700"`
|
||||
- `notes`: Freeform observations from the analyzer
|
||||
|
||||
**Important:** The viewer reads these field names exactly. Using `config` instead of `configuration`, or putting `pass_rate` at the top level of a run instead of nested under `result`, will cause the viewer to show empty/zero values. Always reference this schema when generating benchmark.json manually.
|
||||
|
||||
---
|
||||
|
||||
## comparison.json
|
||||
|
||||
Output from blind comparator. Located at `<grading-dir>/comparison-N.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"winner": "A",
|
||||
"reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.",
|
||||
"rubric": {
|
||||
"A": {
|
||||
"content": {
|
||||
"correctness": 5,
|
||||
"completeness": 5,
|
||||
"accuracy": 4
|
||||
},
|
||||
"structure": {
|
||||
"organization": 4,
|
||||
"formatting": 5,
|
||||
"usability": 4
|
||||
},
|
||||
"content_score": 4.7,
|
||||
"structure_score": 4.3,
|
||||
"overall_score": 9.0
|
||||
},
|
||||
"B": {
|
||||
"content": {
|
||||
"correctness": 3,
|
||||
"completeness": 2,
|
||||
"accuracy": 3
|
||||
},
|
||||
"structure": {
|
||||
"organization": 3,
|
||||
"formatting": 2,
|
||||
"usability": 3
|
||||
},
|
||||
"content_score": 2.7,
|
||||
"structure_score": 2.7,
|
||||
"overall_score": 5.4
|
||||
}
|
||||
},
|
||||
"output_quality": {
|
||||
"A": {
|
||||
"score": 9,
|
||||
"strengths": ["Complete solution", "Well-formatted", "All fields present"],
|
||||
"weaknesses": ["Minor style inconsistency in header"]
|
||||
},
|
||||
"B": {
|
||||
"score": 5,
|
||||
"strengths": ["Readable output", "Correct basic structure"],
|
||||
"weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"]
|
||||
}
|
||||
},
|
||||
"expectation_results": {
|
||||
"A": {
|
||||
"passed": 4,
|
||||
"total": 5,
|
||||
"pass_rate": 0.80,
|
||||
"details": [
|
||||
{"text": "Output includes name", "passed": true}
|
||||
]
|
||||
},
|
||||
"B": {
|
||||
"passed": 3,
|
||||
"total": 5,
|
||||
"pass_rate": 0.60,
|
||||
"details": [
|
||||
{"text": "Output includes name", "passed": true}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## analysis.json
|
||||
|
||||
Output from post-hoc analyzer. Located at `<grading-dir>/analysis.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"comparison_summary": {
|
||||
"winner": "A",
|
||||
"winner_skill": "path/to/winner/skill",
|
||||
"loser_skill": "path/to/loser/skill",
|
||||
"comparator_reasoning": "Brief summary of why comparator chose winner"
|
||||
},
|
||||
"winner_strengths": [
|
||||
"Clear step-by-step instructions for handling multi-page documents",
|
||||
"Included validation script that caught formatting errors"
|
||||
],
|
||||
"loser_weaknesses": [
|
||||
"Vague instruction 'process the document appropriately' led to inconsistent behavior",
|
||||
"No script for validation, agent had to improvise"
|
||||
],
|
||||
"instruction_following": {
|
||||
"winner": {
|
||||
"score": 9,
|
||||
"issues": ["Minor: skipped optional logging step"]
|
||||
},
|
||||
"loser": {
|
||||
"score": 6,
|
||||
"issues": [
|
||||
"Did not use the skill's formatting template",
|
||||
"Invented own approach instead of following step 3"
|
||||
]
|
||||
}
|
||||
},
|
||||
"improvement_suggestions": [
|
||||
{
|
||||
"priority": "high",
|
||||
"category": "instructions",
|
||||
"suggestion": "Replace 'process the document appropriately' with explicit steps",
|
||||
"expected_impact": "Would eliminate ambiguity that caused inconsistent behavior"
|
||||
}
|
||||
],
|
||||
"transcript_insights": {
|
||||
"winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script",
|
||||
"loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,401 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Aggregate individual run results into benchmark summary statistics.
|
||||
|
||||
Reads grading.json files from run directories and produces:
|
||||
- run_summary with mean, stddev, min, max for each metric
|
||||
- delta between with_skill and without_skill configurations
|
||||
|
||||
Usage:
|
||||
python aggregate_benchmark.py <benchmark_dir>
|
||||
|
||||
Example:
|
||||
python aggregate_benchmark.py benchmarks/2026-01-15T10-30-00/
|
||||
|
||||
The script supports two directory layouts:
|
||||
|
||||
Workspace layout (from skill-creator iterations):
|
||||
<benchmark_dir>/
|
||||
└── eval-N/
|
||||
├── with_skill/
|
||||
│ ├── run-1/grading.json
|
||||
│ └── run-2/grading.json
|
||||
└── without_skill/
|
||||
├── run-1/grading.json
|
||||
└── run-2/grading.json
|
||||
|
||||
Legacy layout (with runs/ subdirectory):
|
||||
<benchmark_dir>/
|
||||
└── runs/
|
||||
└── eval-N/
|
||||
├── with_skill/
|
||||
│ └── run-1/grading.json
|
||||
└── without_skill/
|
||||
└── run-1/grading.json
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def calculate_stats(values: list[float]) -> dict:
|
||||
"""Calculate mean, stddev, min, max for a list of values."""
|
||||
if not values:
|
||||
return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}
|
||||
|
||||
n = len(values)
|
||||
mean = sum(values) / n
|
||||
|
||||
if n > 1:
|
||||
variance = sum((x - mean) ** 2 for x in values) / (n - 1)
|
||||
stddev = math.sqrt(variance)
|
||||
else:
|
||||
stddev = 0.0
|
||||
|
||||
return {
|
||||
"mean": round(mean, 4),
|
||||
"stddev": round(stddev, 4),
|
||||
"min": round(min(values), 4),
|
||||
"max": round(max(values), 4)
|
||||
}
|
||||
|
||||
|
||||
def load_run_results(benchmark_dir: Path) -> dict:
|
||||
"""
|
||||
Load all run results from a benchmark directory.
|
||||
|
||||
Returns dict keyed by config name (e.g. "with_skill"/"without_skill",
|
||||
or "new_skill"/"old_skill"), each containing a list of run results.
|
||||
"""
|
||||
# Support both layouts: eval dirs directly under benchmark_dir, or under runs/
|
||||
runs_dir = benchmark_dir / "runs"
|
||||
if runs_dir.exists():
|
||||
search_dir = runs_dir
|
||||
elif list(benchmark_dir.glob("eval-*")):
|
||||
search_dir = benchmark_dir
|
||||
else:
|
||||
print(f"No eval directories found in {benchmark_dir} or {benchmark_dir / 'runs'}")
|
||||
return {}
|
||||
|
||||
results: dict[str, list] = {}
|
||||
|
||||
for eval_idx, eval_dir in enumerate(sorted(search_dir.glob("eval-*"))):
|
||||
metadata_path = eval_dir / "eval_metadata.json"
|
||||
if metadata_path.exists():
|
||||
try:
|
||||
with open(metadata_path) as mf:
|
||||
eval_id = json.load(mf).get("eval_id", eval_idx)
|
||||
except (json.JSONDecodeError, OSError):
|
||||
eval_id = eval_idx
|
||||
else:
|
||||
try:
|
||||
eval_id = int(eval_dir.name.split("-")[1])
|
||||
except ValueError:
|
||||
eval_id = eval_idx
|
||||
|
||||
# Discover config directories dynamically rather than hardcoding names
|
||||
for config_dir in sorted(eval_dir.iterdir()):
|
||||
if not config_dir.is_dir():
|
||||
continue
|
||||
# Skip non-config directories (inputs, outputs, etc.)
|
||||
if not list(config_dir.glob("run-*")):
|
||||
continue
|
||||
config = config_dir.name
|
||||
if config not in results:
|
||||
results[config] = []
|
||||
|
||||
for run_dir in sorted(config_dir.glob("run-*")):
|
||||
run_number = int(run_dir.name.split("-")[1])
|
||||
grading_file = run_dir / "grading.json"
|
||||
|
||||
if not grading_file.exists():
|
||||
print(f"Warning: grading.json not found in {run_dir}")
|
||||
continue
|
||||
|
||||
try:
|
||||
with open(grading_file) as f:
|
||||
grading = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Warning: Invalid JSON in {grading_file}: {e}")
|
||||
continue
|
||||
|
||||
# Extract metrics
|
||||
result = {
|
||||
"eval_id": eval_id,
|
||||
"run_number": run_number,
|
||||
"pass_rate": grading.get("summary", {}).get("pass_rate", 0.0),
|
||||
"passed": grading.get("summary", {}).get("passed", 0),
|
||||
"failed": grading.get("summary", {}).get("failed", 0),
|
||||
"total": grading.get("summary", {}).get("total", 0),
|
||||
}
|
||||
|
||||
# Extract timing — check grading.json first, then sibling timing.json
|
||||
timing = grading.get("timing", {})
|
||||
result["time_seconds"] = timing.get("total_duration_seconds", 0.0)
|
||||
timing_file = run_dir / "timing.json"
|
||||
if result["time_seconds"] == 0.0 and timing_file.exists():
|
||||
try:
|
||||
with open(timing_file) as tf:
|
||||
timing_data = json.load(tf)
|
||||
result["time_seconds"] = timing_data.get("total_duration_seconds", 0.0)
|
||||
result["tokens"] = timing_data.get("total_tokens", 0)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# Extract metrics if available
|
||||
metrics = grading.get("execution_metrics", {})
|
||||
result["tool_calls"] = metrics.get("total_tool_calls", 0)
|
||||
if not result.get("tokens"):
|
||||
result["tokens"] = metrics.get("output_chars", 0)
|
||||
result["errors"] = metrics.get("errors_encountered", 0)
|
||||
|
||||
# Extract expectations — viewer requires fields: text, passed, evidence
|
||||
raw_expectations = grading.get("expectations", [])
|
||||
for exp in raw_expectations:
|
||||
if "text" not in exp or "passed" not in exp:
|
||||
print(f"Warning: expectation in {grading_file} missing required fields (text, passed, evidence): {exp}")
|
||||
result["expectations"] = raw_expectations
|
||||
|
||||
# Extract notes from user_notes_summary
|
||||
notes_summary = grading.get("user_notes_summary", {})
|
||||
notes = []
|
||||
notes.extend(notes_summary.get("uncertainties", []))
|
||||
notes.extend(notes_summary.get("needs_review", []))
|
||||
notes.extend(notes_summary.get("workarounds", []))
|
||||
result["notes"] = notes
|
||||
|
||||
results[config].append(result)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def aggregate_results(results: dict) -> dict:
|
||||
"""
|
||||
Aggregate run results into summary statistics.
|
||||
|
||||
Returns run_summary with stats for each configuration and delta.
|
||||
"""
|
||||
run_summary = {}
|
||||
configs = list(results.keys())
|
||||
|
||||
for config in configs:
|
||||
runs = results.get(config, [])
|
||||
|
||||
if not runs:
|
||||
run_summary[config] = {
|
||||
"pass_rate": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0},
|
||||
"time_seconds": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0},
|
||||
"tokens": {"mean": 0, "stddev": 0, "min": 0, "max": 0}
|
||||
}
|
||||
continue
|
||||
|
||||
pass_rates = [r["pass_rate"] for r in runs]
|
||||
times = [r["time_seconds"] for r in runs]
|
||||
tokens = [r.get("tokens", 0) for r in runs]
|
||||
|
||||
run_summary[config] = {
|
||||
"pass_rate": calculate_stats(pass_rates),
|
||||
"time_seconds": calculate_stats(times),
|
||||
"tokens": calculate_stats(tokens)
|
||||
}
|
||||
|
||||
# Calculate delta between the first two configs (if two exist)
|
||||
if len(configs) >= 2:
|
||||
primary = run_summary.get(configs[0], {})
|
||||
baseline = run_summary.get(configs[1], {})
|
||||
else:
|
||||
primary = run_summary.get(configs[0], {}) if configs else {}
|
||||
baseline = {}
|
||||
|
||||
delta_pass_rate = primary.get("pass_rate", {}).get("mean", 0) - baseline.get("pass_rate", {}).get("mean", 0)
|
||||
delta_time = primary.get("time_seconds", {}).get("mean", 0) - baseline.get("time_seconds", {}).get("mean", 0)
|
||||
delta_tokens = primary.get("tokens", {}).get("mean", 0) - baseline.get("tokens", {}).get("mean", 0)
|
||||
|
||||
run_summary["delta"] = {
|
||||
"pass_rate": f"{delta_pass_rate:+.2f}",
|
||||
"time_seconds": f"{delta_time:+.1f}",
|
||||
"tokens": f"{delta_tokens:+.0f}"
|
||||
}
|
||||
|
||||
return run_summary
|
||||
|
||||
|
||||
def generate_benchmark(benchmark_dir: Path, skill_name: str = "", skill_path: str = "") -> dict:
|
||||
"""
|
||||
Generate complete benchmark.json from run results.
|
||||
"""
|
||||
results = load_run_results(benchmark_dir)
|
||||
run_summary = aggregate_results(results)
|
||||
|
||||
# Build runs array for benchmark.json
|
||||
runs = []
|
||||
for config in results:
|
||||
for result in results[config]:
|
||||
runs.append({
|
||||
"eval_id": result["eval_id"],
|
||||
"configuration": config,
|
||||
"run_number": result["run_number"],
|
||||
"result": {
|
||||
"pass_rate": result["pass_rate"],
|
||||
"passed": result["passed"],
|
||||
"failed": result["failed"],
|
||||
"total": result["total"],
|
||||
"time_seconds": result["time_seconds"],
|
||||
"tokens": result.get("tokens", 0),
|
||||
"tool_calls": result.get("tool_calls", 0),
|
||||
"errors": result.get("errors", 0)
|
||||
},
|
||||
"expectations": result["expectations"],
|
||||
"notes": result["notes"]
|
||||
})
|
||||
|
||||
# Determine eval IDs from results
|
||||
eval_ids = sorted(set(
|
||||
r["eval_id"]
|
||||
for config in results.values()
|
||||
for r in config
|
||||
))
|
||||
|
||||
benchmark = {
|
||||
"metadata": {
|
||||
"skill_name": skill_name or "<skill-name>",
|
||||
"skill_path": skill_path or "<path/to/skill>",
|
||||
"executor_model": "<model-name>",
|
||||
"analyzer_model": "<model-name>",
|
||||
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"evals_run": eval_ids,
|
||||
"runs_per_configuration": 3
|
||||
},
|
||||
"runs": runs,
|
||||
"run_summary": run_summary,
|
||||
"notes": [] # To be filled by analyzer
|
||||
}
|
||||
|
||||
return benchmark
|
||||
|
||||
|
||||
def generate_markdown(benchmark: dict) -> str:
|
||||
"""Generate human-readable benchmark.md from benchmark data."""
|
||||
metadata = benchmark["metadata"]
|
||||
run_summary = benchmark["run_summary"]
|
||||
|
||||
# Determine config names (excluding "delta")
|
||||
configs = [k for k in run_summary if k != "delta"]
|
||||
config_a = configs[0] if len(configs) >= 1 else "config_a"
|
||||
config_b = configs[1] if len(configs) >= 2 else "config_b"
|
||||
label_a = config_a.replace("_", " ").title()
|
||||
label_b = config_b.replace("_", " ").title()
|
||||
|
||||
lines = [
|
||||
f"# Skill Benchmark: {metadata['skill_name']}",
|
||||
"",
|
||||
f"**Model**: {metadata['executor_model']}",
|
||||
f"**Date**: {metadata['timestamp']}",
|
||||
f"**Evals**: {', '.join(map(str, metadata['evals_run']))} ({metadata['runs_per_configuration']} runs each per configuration)",
|
||||
"",
|
||||
"## Summary",
|
||||
"",
|
||||
f"| Metric | {label_a} | {label_b} | Delta |",
|
||||
"|--------|------------|---------------|-------|",
|
||||
]
|
||||
|
||||
a_summary = run_summary.get(config_a, {})
|
||||
b_summary = run_summary.get(config_b, {})
|
||||
delta = run_summary.get("delta", {})
|
||||
|
||||
# Format pass rate
|
||||
a_pr = a_summary.get("pass_rate", {})
|
||||
b_pr = b_summary.get("pass_rate", {})
|
||||
lines.append(f"| Pass Rate | {a_pr.get('mean', 0)*100:.0f}% ± {a_pr.get('stddev', 0)*100:.0f}% | {b_pr.get('mean', 0)*100:.0f}% ± {b_pr.get('stddev', 0)*100:.0f}% | {delta.get('pass_rate', '—')} |")
|
||||
|
||||
# Format time
|
||||
a_time = a_summary.get("time_seconds", {})
|
||||
b_time = b_summary.get("time_seconds", {})
|
||||
lines.append(f"| Time | {a_time.get('mean', 0):.1f}s ± {a_time.get('stddev', 0):.1f}s | {b_time.get('mean', 0):.1f}s ± {b_time.get('stddev', 0):.1f}s | {delta.get('time_seconds', '—')}s |")
|
||||
|
||||
# Format tokens
|
||||
a_tokens = a_summary.get("tokens", {})
|
||||
b_tokens = b_summary.get("tokens", {})
|
||||
lines.append(f"| Tokens | {a_tokens.get('mean', 0):.0f} ± {a_tokens.get('stddev', 0):.0f} | {b_tokens.get('mean', 0):.0f} ± {b_tokens.get('stddev', 0):.0f} | {delta.get('tokens', '—')} |")
|
||||
|
||||
# Notes section
|
||||
if benchmark.get("notes"):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Notes",
|
||||
""
|
||||
])
|
||||
for note in benchmark["notes"]:
|
||||
lines.append(f"- {note}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Aggregate benchmark run results into summary statistics"
|
||||
)
|
||||
parser.add_argument(
|
||||
"benchmark_dir",
|
||||
type=Path,
|
||||
help="Path to the benchmark directory"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skill-name",
|
||||
default="",
|
||||
help="Name of the skill being benchmarked"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skill-path",
|
||||
default="",
|
||||
help="Path to the skill being benchmarked"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
type=Path,
|
||||
help="Output path for benchmark.json (default: <benchmark_dir>/benchmark.json)"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.benchmark_dir.exists():
|
||||
print(f"Directory not found: {args.benchmark_dir}")
|
||||
sys.exit(1)
|
||||
|
||||
# Generate benchmark
|
||||
benchmark = generate_benchmark(args.benchmark_dir, args.skill_name, args.skill_path)
|
||||
|
||||
# Determine output paths
|
||||
output_json = args.output or (args.benchmark_dir / "benchmark.json")
|
||||
output_md = output_json.with_suffix(".md")
|
||||
|
||||
# Write benchmark.json
|
||||
with open(output_json, "w") as f:
|
||||
json.dump(benchmark, f, indent=2)
|
||||
print(f"Generated: {output_json}")
|
||||
|
||||
# Write benchmark.md
|
||||
markdown = generate_markdown(benchmark)
|
||||
with open(output_md, "w") as f:
|
||||
f.write(markdown)
|
||||
print(f"Generated: {output_md}")
|
||||
|
||||
# Print summary
|
||||
run_summary = benchmark["run_summary"]
|
||||
configs = [k for k in run_summary if k != "delta"]
|
||||
delta = run_summary.get("delta", {})
|
||||
|
||||
print(f"\nSummary:")
|
||||
for config in configs:
|
||||
pr = run_summary[config]["pass_rate"]["mean"]
|
||||
label = config.replace("_", " ").title()
|
||||
print(f" {label}: {pr*100:.1f}% pass rate")
|
||||
print(f" Delta: {delta.get('pass_rate', '—')}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,326 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate an HTML report from run_loop.py output.
|
||||
|
||||
Takes the JSON output from run_loop.py and generates a visual HTML report
|
||||
showing each description attempt with check/x for each test case.
|
||||
Distinguishes between train and test queries.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str:
|
||||
"""Generate HTML report from loop output data. If auto_refresh is True, adds a meta refresh tag."""
|
||||
history = data.get("history", [])
|
||||
holdout = data.get("holdout", 0)
|
||||
title_prefix = html.escape(skill_name + " \u2014 ") if skill_name else ""
|
||||
|
||||
# Get all unique queries from train and test sets, with should_trigger info
|
||||
train_queries: list[dict] = []
|
||||
test_queries: list[dict] = []
|
||||
if history:
|
||||
for r in history[0].get("train_results", history[0].get("results", [])):
|
||||
train_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)})
|
||||
if history[0].get("test_results"):
|
||||
for r in history[0].get("test_results", []):
|
||||
test_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)})
|
||||
|
||||
refresh_tag = ' <meta http-equiv="refresh" content="5">\n' if auto_refresh else ""
|
||||
|
||||
html_parts = ["""<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
""" + refresh_tag + """ <title>""" + title_prefix + """Skill Description Optimization</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Lora', Georgia, serif;
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
background: #faf9f5;
|
||||
color: #141413;
|
||||
}
|
||||
h1 { font-family: 'Poppins', sans-serif; color: #141413; }
|
||||
.explainer {
|
||||
background: white;
|
||||
padding: 15px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 20px;
|
||||
border: 1px solid #e8e6dc;
|
||||
color: #b0aea5;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.summary {
|
||||
background: white;
|
||||
padding: 15px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 20px;
|
||||
border: 1px solid #e8e6dc;
|
||||
}
|
||||
.summary p { margin: 5px 0; }
|
||||
.best { color: #788c5d; font-weight: bold; }
|
||||
.table-container {
|
||||
overflow-x: auto;
|
||||
width: 100%;
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
background: white;
|
||||
border: 1px solid #e8e6dc;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
min-width: 100%;
|
||||
}
|
||||
th, td {
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
border: 1px solid #e8e6dc;
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
th {
|
||||
font-family: 'Poppins', sans-serif;
|
||||
background: #141413;
|
||||
color: #faf9f5;
|
||||
font-weight: 500;
|
||||
}
|
||||
th.test-col {
|
||||
background: #6a9bcc;
|
||||
}
|
||||
th.query-col { min-width: 200px; }
|
||||
td.description {
|
||||
font-family: monospace;
|
||||
font-size: 11px;
|
||||
word-wrap: break-word;
|
||||
max-width: 400px;
|
||||
}
|
||||
td.result {
|
||||
text-align: center;
|
||||
font-size: 16px;
|
||||
min-width: 40px;
|
||||
}
|
||||
td.test-result {
|
||||
background: #f0f6fc;
|
||||
}
|
||||
.pass { color: #788c5d; }
|
||||
.fail { color: #c44; }
|
||||
.rate {
|
||||
font-size: 9px;
|
||||
color: #b0aea5;
|
||||
display: block;
|
||||
}
|
||||
tr:hover { background: #faf9f5; }
|
||||
.score {
|
||||
display: inline-block;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-weight: bold;
|
||||
font-size: 11px;
|
||||
}
|
||||
.score-good { background: #eef2e8; color: #788c5d; }
|
||||
.score-ok { background: #fef3c7; color: #d97706; }
|
||||
.score-bad { background: #fceaea; color: #c44; }
|
||||
.train-label { color: #b0aea5; font-size: 10px; }
|
||||
.test-label { color: #6a9bcc; font-size: 10px; font-weight: bold; }
|
||||
.best-row { background: #f5f8f2; }
|
||||
th.positive-col { border-bottom: 3px solid #788c5d; }
|
||||
th.negative-col { border-bottom: 3px solid #c44; }
|
||||
th.test-col.positive-col { border-bottom: 3px solid #788c5d; }
|
||||
th.test-col.negative-col { border-bottom: 3px solid #c44; }
|
||||
.legend { font-family: 'Poppins', sans-serif; display: flex; gap: 20px; margin-bottom: 10px; font-size: 13px; align-items: center; }
|
||||
.legend-item { display: flex; align-items: center; gap: 6px; }
|
||||
.legend-swatch { width: 16px; height: 16px; border-radius: 3px; display: inline-block; }
|
||||
.swatch-positive { background: #141413; border-bottom: 3px solid #788c5d; }
|
||||
.swatch-negative { background: #141413; border-bottom: 3px solid #c44; }
|
||||
.swatch-test { background: #6a9bcc; }
|
||||
.swatch-train { background: #141413; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>""" + title_prefix + """Skill Description Optimization</h1>
|
||||
<div class="explainer">
|
||||
<strong>Optimizing your skill's description.</strong> This page updates automatically as Claude tests different versions of your skill's description. Each row is an iteration — a new description attempt. The columns show test queries: green checkmarks mean the skill triggered correctly (or correctly didn't trigger), red crosses mean it got it wrong. The "Train" score shows performance on queries used to improve the description; the "Test" score shows performance on held-out queries the optimizer hasn't seen. When it's done, Claude will apply the best-performing description to your skill.
|
||||
</div>
|
||||
"""]
|
||||
|
||||
# Summary section
|
||||
best_test_score = data.get('best_test_score')
|
||||
best_train_score = data.get('best_train_score')
|
||||
html_parts.append(f"""
|
||||
<div class="summary">
|
||||
<p><strong>Original:</strong> {html.escape(data.get('original_description', 'N/A'))}</p>
|
||||
<p class="best"><strong>Best:</strong> {html.escape(data.get('best_description', 'N/A'))}</p>
|
||||
<p><strong>Best Score:</strong> {data.get('best_score', 'N/A')} {'(test)' if best_test_score else '(train)'}</p>
|
||||
<p><strong>Iterations:</strong> {data.get('iterations_run', 0)} | <strong>Train:</strong> {data.get('train_size', '?')} | <strong>Test:</strong> {data.get('test_size', '?')}</p>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# Legend
|
||||
html_parts.append("""
|
||||
<div class="legend">
|
||||
<span style="font-weight:600">Query columns:</span>
|
||||
<span class="legend-item"><span class="legend-swatch swatch-positive"></span> Should trigger</span>
|
||||
<span class="legend-item"><span class="legend-swatch swatch-negative"></span> Should NOT trigger</span>
|
||||
<span class="legend-item"><span class="legend-swatch swatch-train"></span> Train</span>
|
||||
<span class="legend-item"><span class="legend-swatch swatch-test"></span> Test</span>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# Table header
|
||||
html_parts.append("""
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Iter</th>
|
||||
<th>Train</th>
|
||||
<th>Test</th>
|
||||
<th class="query-col">Description</th>
|
||||
""")
|
||||
|
||||
# Add column headers for train queries
|
||||
for qinfo in train_queries:
|
||||
polarity = "positive-col" if qinfo["should_trigger"] else "negative-col"
|
||||
html_parts.append(f' <th class="{polarity}">{html.escape(qinfo["query"])}</th>\n')
|
||||
|
||||
# Add column headers for test queries (different color)
|
||||
for qinfo in test_queries:
|
||||
polarity = "positive-col" if qinfo["should_trigger"] else "negative-col"
|
||||
html_parts.append(f' <th class="test-col {polarity}">{html.escape(qinfo["query"])}</th>\n')
|
||||
|
||||
html_parts.append(""" </tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""")
|
||||
|
||||
# Find best iteration for highlighting
|
||||
if test_queries:
|
||||
best_iter = max(history, key=lambda h: h.get("test_passed") or 0).get("iteration")
|
||||
else:
|
||||
best_iter = max(history, key=lambda h: h.get("train_passed", h.get("passed", 0))).get("iteration")
|
||||
|
||||
# Add rows for each iteration
|
||||
for h in history:
|
||||
iteration = h.get("iteration", "?")
|
||||
train_passed = h.get("train_passed", h.get("passed", 0))
|
||||
train_total = h.get("train_total", h.get("total", 0))
|
||||
test_passed = h.get("test_passed")
|
||||
test_total = h.get("test_total")
|
||||
description = h.get("description", "")
|
||||
train_results = h.get("train_results", h.get("results", []))
|
||||
test_results = h.get("test_results", [])
|
||||
|
||||
# Create lookups for results by query
|
||||
train_by_query = {r["query"]: r for r in train_results}
|
||||
test_by_query = {r["query"]: r for r in test_results} if test_results else {}
|
||||
|
||||
# Compute aggregate correct/total runs across all retries
|
||||
def aggregate_runs(results: list[dict]) -> tuple[int, int]:
|
||||
correct = 0
|
||||
total = 0
|
||||
for r in results:
|
||||
runs = r.get("runs", 0)
|
||||
triggers = r.get("triggers", 0)
|
||||
total += runs
|
||||
if r.get("should_trigger", True):
|
||||
correct += triggers
|
||||
else:
|
||||
correct += runs - triggers
|
||||
return correct, total
|
||||
|
||||
train_correct, train_runs = aggregate_runs(train_results)
|
||||
test_correct, test_runs = aggregate_runs(test_results)
|
||||
|
||||
# Determine score classes
|
||||
def score_class(correct: int, total: int) -> str:
|
||||
if total > 0:
|
||||
ratio = correct / total
|
||||
if ratio >= 0.8:
|
||||
return "score-good"
|
||||
elif ratio >= 0.5:
|
||||
return "score-ok"
|
||||
return "score-bad"
|
||||
|
||||
train_class = score_class(train_correct, train_runs)
|
||||
test_class = score_class(test_correct, test_runs)
|
||||
|
||||
row_class = "best-row" if iteration == best_iter else ""
|
||||
|
||||
html_parts.append(f""" <tr class="{row_class}">
|
||||
<td>{iteration}</td>
|
||||
<td><span class="score {train_class}">{train_correct}/{train_runs}</span></td>
|
||||
<td><span class="score {test_class}">{test_correct}/{test_runs}</span></td>
|
||||
<td class="description">{html.escape(description)}</td>
|
||||
""")
|
||||
|
||||
# Add result for each train query
|
||||
for qinfo in train_queries:
|
||||
r = train_by_query.get(qinfo["query"], {})
|
||||
did_pass = r.get("pass", False)
|
||||
triggers = r.get("triggers", 0)
|
||||
runs = r.get("runs", 0)
|
||||
|
||||
icon = "✓" if did_pass else "✗"
|
||||
css_class = "pass" if did_pass else "fail"
|
||||
|
||||
html_parts.append(f' <td class="result {css_class}">{icon}<span class="rate">{triggers}/{runs}</span></td>\n')
|
||||
|
||||
# Add result for each test query (with different background)
|
||||
for qinfo in test_queries:
|
||||
r = test_by_query.get(qinfo["query"], {})
|
||||
did_pass = r.get("pass", False)
|
||||
triggers = r.get("triggers", 0)
|
||||
runs = r.get("runs", 0)
|
||||
|
||||
icon = "✓" if did_pass else "✗"
|
||||
css_class = "pass" if did_pass else "fail"
|
||||
|
||||
html_parts.append(f' <td class="result test-result {css_class}">{icon}<span class="rate">{triggers}/{runs}</span></td>\n')
|
||||
|
||||
html_parts.append(" </tr>\n")
|
||||
|
||||
html_parts.append(""" </tbody>
|
||||
</table>
|
||||
</div>
|
||||
""")
|
||||
|
||||
html_parts.append("""
|
||||
</body>
|
||||
</html>
|
||||
""")
|
||||
|
||||
return "".join(html_parts)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate HTML report from run_loop output")
|
||||
parser.add_argument("input", help="Path to JSON output from run_loop.py (or - for stdin)")
|
||||
parser.add_argument("-o", "--output", default=None, help="Output HTML file (default: stdout)")
|
||||
parser.add_argument("--skill-name", default="", help="Skill name to include in the report title")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.input == "-":
|
||||
data = json.load(sys.stdin)
|
||||
else:
|
||||
data = json.loads(Path(args.input).read_text())
|
||||
|
||||
html_output = generate_html(data, skill_name=args.skill_name)
|
||||
|
||||
if args.output:
|
||||
Path(args.output).write_text(html_output)
|
||||
print(f"Report written to {args.output}", file=sys.stderr)
|
||||
else:
|
||||
print(html_output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,247 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Improve a skill description based on eval results.
|
||||
|
||||
Takes eval results (from run_eval.py) and generates an improved description
|
||||
by calling `claude -p` as a subprocess (same auth pattern as run_eval.py —
|
||||
uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from scripts.utils import parse_skill_md
|
||||
|
||||
|
||||
def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str:
|
||||
"""Run `claude -p` with the prompt on stdin and return the text response.
|
||||
|
||||
Prompt goes over stdin (not argv) because it embeds the full SKILL.md
|
||||
body and can easily exceed comfortable argv length.
|
||||
"""
|
||||
cmd = ["claude", "-p", "--output-format", "text"]
|
||||
if model:
|
||||
cmd.extend(["--model", model])
|
||||
|
||||
# Remove CLAUDECODE env var to allow nesting claude -p inside a
|
||||
# Claude Code session. The guard is for interactive terminal conflicts;
|
||||
# programmatic subprocess usage is safe. Same pattern as run_eval.py.
|
||||
env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
|
||||
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
input=prompt,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"claude -p exited {result.returncode}\nstderr: {result.stderr}"
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def improve_description(
|
||||
skill_name: str,
|
||||
skill_content: str,
|
||||
current_description: str,
|
||||
eval_results: dict,
|
||||
history: list[dict],
|
||||
model: str,
|
||||
test_results: dict | None = None,
|
||||
log_dir: Path | None = None,
|
||||
iteration: int | None = None,
|
||||
) -> str:
|
||||
"""Call Claude to improve the description based on eval results."""
|
||||
failed_triggers = [
|
||||
r for r in eval_results["results"]
|
||||
if r["should_trigger"] and not r["pass"]
|
||||
]
|
||||
false_triggers = [
|
||||
r for r in eval_results["results"]
|
||||
if not r["should_trigger"] and not r["pass"]
|
||||
]
|
||||
|
||||
# Build scores summary
|
||||
train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}"
|
||||
if test_results:
|
||||
test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}"
|
||||
scores_summary = f"Train: {train_score}, Test: {test_score}"
|
||||
else:
|
||||
scores_summary = f"Train: {train_score}"
|
||||
|
||||
prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples.
|
||||
|
||||
The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones.
|
||||
|
||||
Here's the current description:
|
||||
<current_description>
|
||||
"{current_description}"
|
||||
</current_description>
|
||||
|
||||
Current scores ({scores_summary}):
|
||||
<scores_summary>
|
||||
"""
|
||||
if failed_triggers:
|
||||
prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n"
|
||||
for r in failed_triggers:
|
||||
prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
|
||||
prompt += "\n"
|
||||
|
||||
if false_triggers:
|
||||
prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n"
|
||||
for r in false_triggers:
|
||||
prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
|
||||
prompt += "\n"
|
||||
|
||||
if history:
|
||||
prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n"
|
||||
for h in history:
|
||||
train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}"
|
||||
test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None
|
||||
score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "")
|
||||
prompt += f'<attempt {score_str}>\n'
|
||||
prompt += f'Description: "{h["description"]}"\n'
|
||||
if "results" in h:
|
||||
prompt += "Train results:\n"
|
||||
for r in h["results"]:
|
||||
status = "PASS" if r["pass"] else "FAIL"
|
||||
prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n'
|
||||
if h.get("note"):
|
||||
prompt += f'Note: {h["note"]}\n'
|
||||
prompt += "</attempt>\n\n"
|
||||
|
||||
prompt += f"""</scores_summary>
|
||||
|
||||
Skill content (for context on what the skill does):
|
||||
<skill_content>
|
||||
{skill_content}
|
||||
</skill_content>
|
||||
|
||||
Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold:
|
||||
|
||||
1. Avoid overfitting
|
||||
2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description.
|
||||
|
||||
Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it.
|
||||
|
||||
Here are some tips that we've found to work well in writing these descriptions:
|
||||
- The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does"
|
||||
- The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works.
|
||||
- The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable.
|
||||
- If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings.
|
||||
|
||||
I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end.
|
||||
|
||||
Please respond with only the new description text in <new_description> tags, nothing else."""
|
||||
|
||||
text = _call_claude(prompt, model)
|
||||
|
||||
match = re.search(r"<new_description>(.*?)</new_description>", text, re.DOTALL)
|
||||
description = match.group(1).strip().strip('"') if match else text.strip().strip('"')
|
||||
|
||||
transcript: dict = {
|
||||
"iteration": iteration,
|
||||
"prompt": prompt,
|
||||
"response": text,
|
||||
"parsed_description": description,
|
||||
"char_count": len(description),
|
||||
"over_limit": len(description) > 1024,
|
||||
}
|
||||
|
||||
# Safety net: the prompt already states the 1024-char hard limit, but if
|
||||
# the model blew past it anyway, make one fresh single-turn call that
|
||||
# quotes the too-long version and asks for a shorter rewrite. (The old
|
||||
# SDK path did this as a true multi-turn; `claude -p` is one-shot, so we
|
||||
# inline the prior output into the new prompt instead.)
|
||||
if len(description) > 1024:
|
||||
shorten_prompt = (
|
||||
f"{prompt}\n\n"
|
||||
f"---\n\n"
|
||||
f"A previous attempt produced this description, which at "
|
||||
f"{len(description)} characters is over the 1024-character hard limit:\n\n"
|
||||
f'"{description}"\n\n'
|
||||
f"Rewrite it to be under 1024 characters while keeping the most "
|
||||
f"important trigger words and intent coverage. Respond with only "
|
||||
f"the new description in <new_description> tags."
|
||||
)
|
||||
shorten_text = _call_claude(shorten_prompt, model)
|
||||
match = re.search(r"<new_description>(.*?)</new_description>", shorten_text, re.DOTALL)
|
||||
shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"')
|
||||
|
||||
transcript["rewrite_prompt"] = shorten_prompt
|
||||
transcript["rewrite_response"] = shorten_text
|
||||
transcript["rewrite_description"] = shortened
|
||||
transcript["rewrite_char_count"] = len(shortened)
|
||||
description = shortened
|
||||
|
||||
transcript["final_description"] = description
|
||||
|
||||
if log_dir:
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json"
|
||||
log_file.write_text(json.dumps(transcript, indent=2))
|
||||
|
||||
return description
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Improve a skill description based on eval results")
|
||||
parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)")
|
||||
parser.add_argument("--skill-path", required=True, help="Path to skill directory")
|
||||
parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)")
|
||||
parser.add_argument("--model", required=True, help="Model for improvement")
|
||||
parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr")
|
||||
args = parser.parse_args()
|
||||
|
||||
skill_path = Path(args.skill_path)
|
||||
if not (skill_path / "SKILL.md").exists():
|
||||
print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
eval_results = json.loads(Path(args.eval_results).read_text())
|
||||
history = []
|
||||
if args.history:
|
||||
history = json.loads(Path(args.history).read_text())
|
||||
|
||||
name, _, content = parse_skill_md(skill_path)
|
||||
current_description = eval_results["description"]
|
||||
|
||||
if args.verbose:
|
||||
print(f"Current: {current_description}", file=sys.stderr)
|
||||
print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr)
|
||||
|
||||
new_description = improve_description(
|
||||
skill_name=name,
|
||||
skill_content=content,
|
||||
current_description=current_description,
|
||||
eval_results=eval_results,
|
||||
history=history,
|
||||
model=args.model,
|
||||
)
|
||||
|
||||
if args.verbose:
|
||||
print(f"Improved: {new_description}", file=sys.stderr)
|
||||
|
||||
# Output as JSON with both the new description and updated history
|
||||
output = {
|
||||
"description": new_description,
|
||||
"history": history + [{
|
||||
"description": current_description,
|
||||
"passed": eval_results["summary"]["passed"],
|
||||
"failed": eval_results["summary"]["failed"],
|
||||
"total": eval_results["summary"]["total"],
|
||||
"results": eval_results["results"],
|
||||
}],
|
||||
}
|
||||
print(json.dumps(output, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
136
1-Vue3-Dev/.agents/skills/skill-creator/scripts/package_skill.py
Normal file
136
1-Vue3-Dev/.agents/skills/skill-creator/scripts/package_skill.py
Normal file
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Packager - Creates a distributable .skill file of a skill folder
|
||||
|
||||
Usage:
|
||||
python utils/package_skill.py <path/to/skill-folder> [output-directory]
|
||||
|
||||
Example:
|
||||
python utils/package_skill.py skills/public/my-skill
|
||||
python utils/package_skill.py skills/public/my-skill ./dist
|
||||
"""
|
||||
|
||||
import fnmatch
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from scripts.quick_validate import validate_skill
|
||||
|
||||
# Patterns to exclude when packaging skills.
|
||||
EXCLUDE_DIRS = {"__pycache__", "node_modules"}
|
||||
EXCLUDE_GLOBS = {"*.pyc"}
|
||||
EXCLUDE_FILES = {".DS_Store"}
|
||||
# Directories excluded only at the skill root (not when nested deeper).
|
||||
ROOT_EXCLUDE_DIRS = {"evals"}
|
||||
|
||||
|
||||
def should_exclude(rel_path: Path) -> bool:
|
||||
"""Check if a path should be excluded from packaging."""
|
||||
parts = rel_path.parts
|
||||
if any(part in EXCLUDE_DIRS for part in parts):
|
||||
return True
|
||||
# rel_path is relative to skill_path.parent, so parts[0] is the skill
|
||||
# folder name and parts[1] (if present) is the first subdir.
|
||||
if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS:
|
||||
return True
|
||||
name = rel_path.name
|
||||
if name in EXCLUDE_FILES:
|
||||
return True
|
||||
return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS)
|
||||
|
||||
|
||||
def package_skill(skill_path, output_dir=None):
|
||||
"""
|
||||
Package a skill folder into a .skill file.
|
||||
|
||||
Args:
|
||||
skill_path: Path to the skill folder
|
||||
output_dir: Optional output directory for the .skill file (defaults to current directory)
|
||||
|
||||
Returns:
|
||||
Path to the created .skill file, or None if error
|
||||
"""
|
||||
skill_path = Path(skill_path).resolve()
|
||||
|
||||
# Validate skill folder exists
|
||||
if not skill_path.exists():
|
||||
print(f"❌ Error: Skill folder not found: {skill_path}")
|
||||
return None
|
||||
|
||||
if not skill_path.is_dir():
|
||||
print(f"❌ Error: Path is not a directory: {skill_path}")
|
||||
return None
|
||||
|
||||
# Validate SKILL.md exists
|
||||
skill_md = skill_path / "SKILL.md"
|
||||
if not skill_md.exists():
|
||||
print(f"❌ Error: SKILL.md not found in {skill_path}")
|
||||
return None
|
||||
|
||||
# Run validation before packaging
|
||||
print("🔍 Validating skill...")
|
||||
valid, message = validate_skill(skill_path)
|
||||
if not valid:
|
||||
print(f"❌ Validation failed: {message}")
|
||||
print(" Please fix the validation errors before packaging.")
|
||||
return None
|
||||
print(f"✅ {message}\n")
|
||||
|
||||
# Determine output location
|
||||
skill_name = skill_path.name
|
||||
if output_dir:
|
||||
output_path = Path(output_dir).resolve()
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
output_path = Path.cwd()
|
||||
|
||||
skill_filename = output_path / f"{skill_name}.skill"
|
||||
|
||||
# Create the .skill file (zip format)
|
||||
try:
|
||||
with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
# Walk through the skill directory, excluding build artifacts
|
||||
for file_path in skill_path.rglob('*'):
|
||||
if not file_path.is_file():
|
||||
continue
|
||||
arcname = file_path.relative_to(skill_path.parent)
|
||||
if should_exclude(arcname):
|
||||
print(f" Skipped: {arcname}")
|
||||
continue
|
||||
zipf.write(file_path, arcname)
|
||||
print(f" Added: {arcname}")
|
||||
|
||||
print(f"\n✅ Successfully packaged skill to: {skill_filename}")
|
||||
return skill_filename
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating .skill file: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
|
||||
print("\nExample:")
|
||||
print(" python utils/package_skill.py skills/public/my-skill")
|
||||
print(" python utils/package_skill.py skills/public/my-skill ./dist")
|
||||
sys.exit(1)
|
||||
|
||||
skill_path = sys.argv[1]
|
||||
output_dir = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
|
||||
print(f"📦 Packaging skill: {skill_path}")
|
||||
if output_dir:
|
||||
print(f" Output directory: {output_dir}")
|
||||
print()
|
||||
|
||||
result = package_skill(skill_path, output_dir)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick validation script for skills - minimal version
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
def validate_skill(skill_path):
|
||||
"""Basic validation of a skill"""
|
||||
skill_path = Path(skill_path)
|
||||
|
||||
# Check SKILL.md exists
|
||||
skill_md = skill_path / 'SKILL.md'
|
||||
if not skill_md.exists():
|
||||
return False, "SKILL.md not found"
|
||||
|
||||
# Read and validate frontmatter
|
||||
content = skill_md.read_text()
|
||||
if not content.startswith('---'):
|
||||
return False, "No YAML frontmatter found"
|
||||
|
||||
# Extract frontmatter
|
||||
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
|
||||
if not match:
|
||||
return False, "Invalid frontmatter format"
|
||||
|
||||
frontmatter_text = match.group(1)
|
||||
|
||||
# Parse YAML frontmatter
|
||||
try:
|
||||
frontmatter = yaml.safe_load(frontmatter_text)
|
||||
if not isinstance(frontmatter, dict):
|
||||
return False, "Frontmatter must be a YAML dictionary"
|
||||
except yaml.YAMLError as e:
|
||||
return False, f"Invalid YAML in frontmatter: {e}"
|
||||
|
||||
# Define allowed properties
|
||||
ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata', 'compatibility'}
|
||||
|
||||
# Check for unexpected properties (excluding nested keys under metadata)
|
||||
unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES
|
||||
if unexpected_keys:
|
||||
return False, (
|
||||
f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. "
|
||||
f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}"
|
||||
)
|
||||
|
||||
# Check required fields
|
||||
if 'name' not in frontmatter:
|
||||
return False, "Missing 'name' in frontmatter"
|
||||
if 'description' not in frontmatter:
|
||||
return False, "Missing 'description' in frontmatter"
|
||||
|
||||
# Extract name for validation
|
||||
name = frontmatter.get('name', '')
|
||||
if not isinstance(name, str):
|
||||
return False, f"Name must be a string, got {type(name).__name__}"
|
||||
name = name.strip()
|
||||
if name:
|
||||
# Check naming convention (kebab-case: lowercase with hyphens)
|
||||
if not re.match(r'^[a-z0-9-]+$', name):
|
||||
return False, f"Name '{name}' should be kebab-case (lowercase letters, digits, and hyphens only)"
|
||||
if name.startswith('-') or name.endswith('-') or '--' in name:
|
||||
return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
|
||||
# Check name length (max 64 characters per spec)
|
||||
if len(name) > 64:
|
||||
return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters."
|
||||
|
||||
# Extract and validate description
|
||||
description = frontmatter.get('description', '')
|
||||
if not isinstance(description, str):
|
||||
return False, f"Description must be a string, got {type(description).__name__}"
|
||||
description = description.strip()
|
||||
if description:
|
||||
# Check for angle brackets
|
||||
if '<' in description or '>' in description:
|
||||
return False, "Description cannot contain angle brackets (< or >)"
|
||||
# Check description length (max 1024 characters per spec)
|
||||
if len(description) > 1024:
|
||||
return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters."
|
||||
|
||||
# Validate compatibility field if present (optional)
|
||||
compatibility = frontmatter.get('compatibility', '')
|
||||
if compatibility:
|
||||
if not isinstance(compatibility, str):
|
||||
return False, f"Compatibility must be a string, got {type(compatibility).__name__}"
|
||||
if len(compatibility) > 500:
|
||||
return False, f"Compatibility is too long ({len(compatibility)} characters). Maximum is 500 characters."
|
||||
|
||||
return True, "Skill is valid!"
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python quick_validate.py <skill_directory>")
|
||||
sys.exit(1)
|
||||
|
||||
valid, message = validate_skill(sys.argv[1])
|
||||
print(message)
|
||||
sys.exit(0 if valid else 1)
|
||||
310
1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_eval.py
Normal file
310
1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_eval.py
Normal file
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run trigger evaluation for a skill description.
|
||||
|
||||
Tests whether a skill's description causes Claude to trigger (read the skill)
|
||||
for a set of queries. Outputs results as JSON.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
|
||||
from scripts.utils import parse_skill_md
|
||||
|
||||
|
||||
def find_project_root() -> Path:
|
||||
"""Find the project root by walking up from cwd looking for .claude/.
|
||||
|
||||
Mimics how Claude Code discovers its project root, so the command file
|
||||
we create ends up where claude -p will look for it.
|
||||
"""
|
||||
current = Path.cwd()
|
||||
for parent in [current, *current.parents]:
|
||||
if (parent / ".claude").is_dir():
|
||||
return parent
|
||||
return current
|
||||
|
||||
|
||||
def run_single_query(
|
||||
query: str,
|
||||
skill_name: str,
|
||||
skill_description: str,
|
||||
timeout: int,
|
||||
project_root: str,
|
||||
model: str | None = None,
|
||||
) -> bool:
|
||||
"""Run a single query and return whether the skill was triggered.
|
||||
|
||||
Creates a command file in .claude/commands/ so it appears in Claude's
|
||||
available_skills list, then runs `claude -p` with the raw query.
|
||||
Uses --include-partial-messages to detect triggering early from
|
||||
stream events (content_block_start) rather than waiting for the
|
||||
full assistant message, which only arrives after tool execution.
|
||||
"""
|
||||
unique_id = uuid.uuid4().hex[:8]
|
||||
clean_name = f"{skill_name}-skill-{unique_id}"
|
||||
project_commands_dir = Path(project_root) / ".claude" / "commands"
|
||||
command_file = project_commands_dir / f"{clean_name}.md"
|
||||
|
||||
try:
|
||||
project_commands_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Use YAML block scalar to avoid breaking on quotes in description
|
||||
indented_desc = "\n ".join(skill_description.split("\n"))
|
||||
command_content = (
|
||||
f"---\n"
|
||||
f"description: |\n"
|
||||
f" {indented_desc}\n"
|
||||
f"---\n\n"
|
||||
f"# {skill_name}\n\n"
|
||||
f"This skill handles: {skill_description}\n"
|
||||
)
|
||||
command_file.write_text(command_content)
|
||||
|
||||
cmd = [
|
||||
"claude",
|
||||
"-p", query,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--include-partial-messages",
|
||||
]
|
||||
if model:
|
||||
cmd.extend(["--model", model])
|
||||
|
||||
# Remove CLAUDECODE env var to allow nesting claude -p inside a
|
||||
# Claude Code session. The guard is for interactive terminal conflicts;
|
||||
# programmatic subprocess usage is safe.
|
||||
env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
|
||||
|
||||
process = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
cwd=project_root,
|
||||
env=env,
|
||||
)
|
||||
|
||||
triggered = False
|
||||
start_time = time.time()
|
||||
buffer = ""
|
||||
# Track state for stream event detection
|
||||
pending_tool_name = None
|
||||
accumulated_json = ""
|
||||
|
||||
try:
|
||||
while time.time() - start_time < timeout:
|
||||
if process.poll() is not None:
|
||||
remaining = process.stdout.read()
|
||||
if remaining:
|
||||
buffer += remaining.decode("utf-8", errors="replace")
|
||||
break
|
||||
|
||||
ready, _, _ = select.select([process.stdout], [], [], 1.0)
|
||||
if not ready:
|
||||
continue
|
||||
|
||||
chunk = os.read(process.stdout.fileno(), 8192)
|
||||
if not chunk:
|
||||
break
|
||||
buffer += chunk.decode("utf-8", errors="replace")
|
||||
|
||||
while "\n" in buffer:
|
||||
line, buffer = buffer.split("\n", 1)
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
# Early detection via stream events
|
||||
if event.get("type") == "stream_event":
|
||||
se = event.get("event", {})
|
||||
se_type = se.get("type", "")
|
||||
|
||||
if se_type == "content_block_start":
|
||||
cb = se.get("content_block", {})
|
||||
if cb.get("type") == "tool_use":
|
||||
tool_name = cb.get("name", "")
|
||||
if tool_name in ("Skill", "Read"):
|
||||
pending_tool_name = tool_name
|
||||
accumulated_json = ""
|
||||
else:
|
||||
return False
|
||||
|
||||
elif se_type == "content_block_delta" and pending_tool_name:
|
||||
delta = se.get("delta", {})
|
||||
if delta.get("type") == "input_json_delta":
|
||||
accumulated_json += delta.get("partial_json", "")
|
||||
if clean_name in accumulated_json:
|
||||
return True
|
||||
|
||||
elif se_type in ("content_block_stop", "message_stop"):
|
||||
if pending_tool_name:
|
||||
return clean_name in accumulated_json
|
||||
if se_type == "message_stop":
|
||||
return False
|
||||
|
||||
# Fallback: full assistant message
|
||||
elif event.get("type") == "assistant":
|
||||
message = event.get("message", {})
|
||||
for content_item in message.get("content", []):
|
||||
if content_item.get("type") != "tool_use":
|
||||
continue
|
||||
tool_name = content_item.get("name", "")
|
||||
tool_input = content_item.get("input", {})
|
||||
if tool_name == "Skill" and clean_name in tool_input.get("skill", ""):
|
||||
triggered = True
|
||||
elif tool_name == "Read" and clean_name in tool_input.get("file_path", ""):
|
||||
triggered = True
|
||||
return triggered
|
||||
|
||||
elif event.get("type") == "result":
|
||||
return triggered
|
||||
finally:
|
||||
# Clean up process on any exit path (return, exception, timeout)
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
return triggered
|
||||
finally:
|
||||
if command_file.exists():
|
||||
command_file.unlink()
|
||||
|
||||
|
||||
def run_eval(
|
||||
eval_set: list[dict],
|
||||
skill_name: str,
|
||||
description: str,
|
||||
num_workers: int,
|
||||
timeout: int,
|
||||
project_root: Path,
|
||||
runs_per_query: int = 1,
|
||||
trigger_threshold: float = 0.5,
|
||||
model: str | None = None,
|
||||
) -> dict:
|
||||
"""Run the full eval set and return results."""
|
||||
results = []
|
||||
|
||||
with ProcessPoolExecutor(max_workers=num_workers) as executor:
|
||||
future_to_info = {}
|
||||
for item in eval_set:
|
||||
for run_idx in range(runs_per_query):
|
||||
future = executor.submit(
|
||||
run_single_query,
|
||||
item["query"],
|
||||
skill_name,
|
||||
description,
|
||||
timeout,
|
||||
str(project_root),
|
||||
model,
|
||||
)
|
||||
future_to_info[future] = (item, run_idx)
|
||||
|
||||
query_triggers: dict[str, list[bool]] = {}
|
||||
query_items: dict[str, dict] = {}
|
||||
for future in as_completed(future_to_info):
|
||||
item, _ = future_to_info[future]
|
||||
query = item["query"]
|
||||
query_items[query] = item
|
||||
if query not in query_triggers:
|
||||
query_triggers[query] = []
|
||||
try:
|
||||
query_triggers[query].append(future.result())
|
||||
except Exception as e:
|
||||
print(f"Warning: query failed: {e}", file=sys.stderr)
|
||||
query_triggers[query].append(False)
|
||||
|
||||
for query, triggers in query_triggers.items():
|
||||
item = query_items[query]
|
||||
trigger_rate = sum(triggers) / len(triggers)
|
||||
should_trigger = item["should_trigger"]
|
||||
if should_trigger:
|
||||
did_pass = trigger_rate >= trigger_threshold
|
||||
else:
|
||||
did_pass = trigger_rate < trigger_threshold
|
||||
results.append({
|
||||
"query": query,
|
||||
"should_trigger": should_trigger,
|
||||
"trigger_rate": trigger_rate,
|
||||
"triggers": sum(triggers),
|
||||
"runs": len(triggers),
|
||||
"pass": did_pass,
|
||||
})
|
||||
|
||||
passed = sum(1 for r in results if r["pass"])
|
||||
total = len(results)
|
||||
|
||||
return {
|
||||
"skill_name": skill_name,
|
||||
"description": description,
|
||||
"results": results,
|
||||
"summary": {
|
||||
"total": total,
|
||||
"passed": passed,
|
||||
"failed": total - passed,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Run trigger evaluation for a skill description")
|
||||
parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
|
||||
parser.add_argument("--skill-path", required=True, help="Path to skill directory")
|
||||
parser.add_argument("--description", default=None, help="Override description to test")
|
||||
parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
|
||||
parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
|
||||
parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
|
||||
parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
|
||||
parser.add_argument("--model", default=None, help="Model to use for claude -p (default: user's configured model)")
|
||||
parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
|
||||
args = parser.parse_args()
|
||||
|
||||
eval_set = json.loads(Path(args.eval_set).read_text())
|
||||
skill_path = Path(args.skill_path)
|
||||
|
||||
if not (skill_path / "SKILL.md").exists():
|
||||
print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
name, original_description, content = parse_skill_md(skill_path)
|
||||
description = args.description or original_description
|
||||
project_root = find_project_root()
|
||||
|
||||
if args.verbose:
|
||||
print(f"Evaluating: {description}", file=sys.stderr)
|
||||
|
||||
output = run_eval(
|
||||
eval_set=eval_set,
|
||||
skill_name=name,
|
||||
description=description,
|
||||
num_workers=args.num_workers,
|
||||
timeout=args.timeout,
|
||||
project_root=project_root,
|
||||
runs_per_query=args.runs_per_query,
|
||||
trigger_threshold=args.trigger_threshold,
|
||||
model=args.model,
|
||||
)
|
||||
|
||||
if args.verbose:
|
||||
summary = output["summary"]
|
||||
print(f"Results: {summary['passed']}/{summary['total']} passed", file=sys.stderr)
|
||||
for r in output["results"]:
|
||||
status = "PASS" if r["pass"] else "FAIL"
|
||||
rate_str = f"{r['triggers']}/{r['runs']}"
|
||||
print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:70]}", file=sys.stderr)
|
||||
|
||||
print(json.dumps(output, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
328
1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_loop.py
Normal file
328
1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_loop.py
Normal file
@@ -0,0 +1,328 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the eval + improve loop until all pass or max iterations reached.
|
||||
|
||||
Combines run_eval.py and improve_description.py in a loop, tracking history
|
||||
and returning the best description found. Supports train/test split to prevent
|
||||
overfitting.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
from scripts.generate_report import generate_html
|
||||
from scripts.improve_description import improve_description
|
||||
from scripts.run_eval import find_project_root, run_eval
|
||||
from scripts.utils import parse_skill_md
|
||||
|
||||
|
||||
def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:
|
||||
"""Split eval set into train and test sets, stratified by should_trigger."""
|
||||
random.seed(seed)
|
||||
|
||||
# Separate by should_trigger
|
||||
trigger = [e for e in eval_set if e["should_trigger"]]
|
||||
no_trigger = [e for e in eval_set if not e["should_trigger"]]
|
||||
|
||||
# Shuffle each group
|
||||
random.shuffle(trigger)
|
||||
random.shuffle(no_trigger)
|
||||
|
||||
# Calculate split points
|
||||
n_trigger_test = max(1, int(len(trigger) * holdout))
|
||||
n_no_trigger_test = max(1, int(len(no_trigger) * holdout))
|
||||
|
||||
# Split
|
||||
test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]
|
||||
train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]
|
||||
|
||||
return train_set, test_set
|
||||
|
||||
|
||||
def run_loop(
|
||||
eval_set: list[dict],
|
||||
skill_path: Path,
|
||||
description_override: str | None,
|
||||
num_workers: int,
|
||||
timeout: int,
|
||||
max_iterations: int,
|
||||
runs_per_query: int,
|
||||
trigger_threshold: float,
|
||||
holdout: float,
|
||||
model: str,
|
||||
verbose: bool,
|
||||
live_report_path: Path | None = None,
|
||||
log_dir: Path | None = None,
|
||||
) -> dict:
|
||||
"""Run the eval + improvement loop."""
|
||||
project_root = find_project_root()
|
||||
name, original_description, content = parse_skill_md(skill_path)
|
||||
current_description = description_override or original_description
|
||||
|
||||
# Split into train/test if holdout > 0
|
||||
if holdout > 0:
|
||||
train_set, test_set = split_eval_set(eval_set, holdout)
|
||||
if verbose:
|
||||
print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr)
|
||||
else:
|
||||
train_set = eval_set
|
||||
test_set = []
|
||||
|
||||
history = []
|
||||
exit_reason = "unknown"
|
||||
|
||||
for iteration in range(1, max_iterations + 1):
|
||||
if verbose:
|
||||
print(f"\n{'='*60}", file=sys.stderr)
|
||||
print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr)
|
||||
print(f"Description: {current_description}", file=sys.stderr)
|
||||
print(f"{'='*60}", file=sys.stderr)
|
||||
|
||||
# Evaluate train + test together in one batch for parallelism
|
||||
all_queries = train_set + test_set
|
||||
t0 = time.time()
|
||||
all_results = run_eval(
|
||||
eval_set=all_queries,
|
||||
skill_name=name,
|
||||
description=current_description,
|
||||
num_workers=num_workers,
|
||||
timeout=timeout,
|
||||
project_root=project_root,
|
||||
runs_per_query=runs_per_query,
|
||||
trigger_threshold=trigger_threshold,
|
||||
model=model,
|
||||
)
|
||||
eval_elapsed = time.time() - t0
|
||||
|
||||
# Split results back into train/test by matching queries
|
||||
train_queries_set = {q["query"] for q in train_set}
|
||||
train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set]
|
||||
test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set]
|
||||
|
||||
train_passed = sum(1 for r in train_result_list if r["pass"])
|
||||
train_total = len(train_result_list)
|
||||
train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total}
|
||||
train_results = {"results": train_result_list, "summary": train_summary}
|
||||
|
||||
if test_set:
|
||||
test_passed = sum(1 for r in test_result_list if r["pass"])
|
||||
test_total = len(test_result_list)
|
||||
test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total}
|
||||
test_results = {"results": test_result_list, "summary": test_summary}
|
||||
else:
|
||||
test_results = None
|
||||
test_summary = None
|
||||
|
||||
history.append({
|
||||
"iteration": iteration,
|
||||
"description": current_description,
|
||||
"train_passed": train_summary["passed"],
|
||||
"train_failed": train_summary["failed"],
|
||||
"train_total": train_summary["total"],
|
||||
"train_results": train_results["results"],
|
||||
"test_passed": test_summary["passed"] if test_summary else None,
|
||||
"test_failed": test_summary["failed"] if test_summary else None,
|
||||
"test_total": test_summary["total"] if test_summary else None,
|
||||
"test_results": test_results["results"] if test_results else None,
|
||||
# For backward compat with report generator
|
||||
"passed": train_summary["passed"],
|
||||
"failed": train_summary["failed"],
|
||||
"total": train_summary["total"],
|
||||
"results": train_results["results"],
|
||||
})
|
||||
|
||||
# Write live report if path provided
|
||||
if live_report_path:
|
||||
partial_output = {
|
||||
"original_description": original_description,
|
||||
"best_description": current_description,
|
||||
"best_score": "in progress",
|
||||
"iterations_run": len(history),
|
||||
"holdout": holdout,
|
||||
"train_size": len(train_set),
|
||||
"test_size": len(test_set),
|
||||
"history": history,
|
||||
}
|
||||
live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
|
||||
|
||||
if verbose:
|
||||
def print_eval_stats(label, results, elapsed):
|
||||
pos = [r for r in results if r["should_trigger"]]
|
||||
neg = [r for r in results if not r["should_trigger"]]
|
||||
tp = sum(r["triggers"] for r in pos)
|
||||
pos_runs = sum(r["runs"] for r in pos)
|
||||
fn = pos_runs - tp
|
||||
fp = sum(r["triggers"] for r in neg)
|
||||
neg_runs = sum(r["runs"] for r in neg)
|
||||
tn = neg_runs - fp
|
||||
total = tp + tn + fp + fn
|
||||
precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
|
||||
recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
|
||||
accuracy = (tp + tn) / total if total > 0 else 0.0
|
||||
print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr)
|
||||
for r in results:
|
||||
status = "PASS" if r["pass"] else "FAIL"
|
||||
rate_str = f"{r['triggers']}/{r['runs']}"
|
||||
print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr)
|
||||
|
||||
print_eval_stats("Train", train_results["results"], eval_elapsed)
|
||||
if test_summary:
|
||||
print_eval_stats("Test ", test_results["results"], 0)
|
||||
|
||||
if train_summary["failed"] == 0:
|
||||
exit_reason = f"all_passed (iteration {iteration})"
|
||||
if verbose:
|
||||
print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr)
|
||||
break
|
||||
|
||||
if iteration == max_iterations:
|
||||
exit_reason = f"max_iterations ({max_iterations})"
|
||||
if verbose:
|
||||
print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr)
|
||||
break
|
||||
|
||||
# Improve the description based on train results
|
||||
if verbose:
|
||||
print(f"\nImproving description...", file=sys.stderr)
|
||||
|
||||
t0 = time.time()
|
||||
# Strip test scores from history so improvement model can't see them
|
||||
blinded_history = [
|
||||
{k: v for k, v in h.items() if not k.startswith("test_")}
|
||||
for h in history
|
||||
]
|
||||
new_description = improve_description(
|
||||
skill_name=name,
|
||||
skill_content=content,
|
||||
current_description=current_description,
|
||||
eval_results=train_results,
|
||||
history=blinded_history,
|
||||
model=model,
|
||||
log_dir=log_dir,
|
||||
iteration=iteration,
|
||||
)
|
||||
improve_elapsed = time.time() - t0
|
||||
|
||||
if verbose:
|
||||
print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr)
|
||||
|
||||
current_description = new_description
|
||||
|
||||
# Find the best iteration by TEST score (or train if no test set)
|
||||
if test_set:
|
||||
best = max(history, key=lambda h: h["test_passed"] or 0)
|
||||
best_score = f"{best['test_passed']}/{best['test_total']}"
|
||||
else:
|
||||
best = max(history, key=lambda h: h["train_passed"])
|
||||
best_score = f"{best['train_passed']}/{best['train_total']}"
|
||||
|
||||
if verbose:
|
||||
print(f"\nExit reason: {exit_reason}", file=sys.stderr)
|
||||
print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr)
|
||||
|
||||
return {
|
||||
"exit_reason": exit_reason,
|
||||
"original_description": original_description,
|
||||
"best_description": best["description"],
|
||||
"best_score": best_score,
|
||||
"best_train_score": f"{best['train_passed']}/{best['train_total']}",
|
||||
"best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None,
|
||||
"final_description": current_description,
|
||||
"iterations_run": len(history),
|
||||
"holdout": holdout,
|
||||
"train_size": len(train_set),
|
||||
"test_size": len(test_set),
|
||||
"history": history,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Run eval + improve loop")
|
||||
parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
|
||||
parser.add_argument("--skill-path", required=True, help="Path to skill directory")
|
||||
parser.add_argument("--description", default=None, help="Override starting description")
|
||||
parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
|
||||
parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
|
||||
parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations")
|
||||
parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
|
||||
parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
|
||||
parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)")
|
||||
parser.add_argument("--model", required=True, help="Model for improvement")
|
||||
parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
|
||||
parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)")
|
||||
parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here")
|
||||
args = parser.parse_args()
|
||||
|
||||
eval_set = json.loads(Path(args.eval_set).read_text())
|
||||
skill_path = Path(args.skill_path)
|
||||
|
||||
if not (skill_path / "SKILL.md").exists():
|
||||
print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
name, _, _ = parse_skill_md(skill_path)
|
||||
|
||||
# Set up live report path
|
||||
if args.report != "none":
|
||||
if args.report == "auto":
|
||||
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html"
|
||||
else:
|
||||
live_report_path = Path(args.report)
|
||||
# Open the report immediately so the user can watch
|
||||
live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>")
|
||||
webbrowser.open(str(live_report_path))
|
||||
else:
|
||||
live_report_path = None
|
||||
|
||||
# Determine output directory (create before run_loop so logs can be written)
|
||||
if args.results_dir:
|
||||
timestamp = time.strftime("%Y-%m-%d_%H%M%S")
|
||||
results_dir = Path(args.results_dir) / timestamp
|
||||
results_dir.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
results_dir = None
|
||||
|
||||
log_dir = results_dir / "logs" if results_dir else None
|
||||
|
||||
output = run_loop(
|
||||
eval_set=eval_set,
|
||||
skill_path=skill_path,
|
||||
description_override=args.description,
|
||||
num_workers=args.num_workers,
|
||||
timeout=args.timeout,
|
||||
max_iterations=args.max_iterations,
|
||||
runs_per_query=args.runs_per_query,
|
||||
trigger_threshold=args.trigger_threshold,
|
||||
holdout=args.holdout,
|
||||
model=args.model,
|
||||
verbose=args.verbose,
|
||||
live_report_path=live_report_path,
|
||||
log_dir=log_dir,
|
||||
)
|
||||
|
||||
# Save JSON output
|
||||
json_output = json.dumps(output, indent=2)
|
||||
print(json_output)
|
||||
if results_dir:
|
||||
(results_dir / "results.json").write_text(json_output)
|
||||
|
||||
# Write final HTML report (without auto-refresh)
|
||||
if live_report_path:
|
||||
live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))
|
||||
print(f"\nReport: {live_report_path}", file=sys.stderr)
|
||||
|
||||
if results_dir and live_report_path:
|
||||
(results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name))
|
||||
|
||||
if results_dir:
|
||||
print(f"Results saved to: {results_dir}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
47
1-Vue3-Dev/.agents/skills/skill-creator/scripts/utils.py
Normal file
47
1-Vue3-Dev/.agents/skills/skill-creator/scripts/utils.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Shared utilities for skill-creator scripts."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
|
||||
def parse_skill_md(skill_path: Path) -> tuple[str, str, str]:
|
||||
"""Parse a SKILL.md file, returning (name, description, full_content)."""
|
||||
content = (skill_path / "SKILL.md").read_text()
|
||||
lines = content.split("\n")
|
||||
|
||||
if lines[0].strip() != "---":
|
||||
raise ValueError("SKILL.md missing frontmatter (no opening ---)")
|
||||
|
||||
end_idx = None
|
||||
for i, line in enumerate(lines[1:], start=1):
|
||||
if line.strip() == "---":
|
||||
end_idx = i
|
||||
break
|
||||
|
||||
if end_idx is None:
|
||||
raise ValueError("SKILL.md missing frontmatter (no closing ---)")
|
||||
|
||||
name = ""
|
||||
description = ""
|
||||
frontmatter_lines = lines[1:end_idx]
|
||||
i = 0
|
||||
while i < len(frontmatter_lines):
|
||||
line = frontmatter_lines[i]
|
||||
if line.startswith("name:"):
|
||||
name = line[len("name:"):].strip().strip('"').strip("'")
|
||||
elif line.startswith("description:"):
|
||||
value = line[len("description:"):].strip()
|
||||
# Handle YAML multiline indicators (>, |, >-, |-)
|
||||
if value in (">", "|", ">-", "|-"):
|
||||
continuation_lines: list[str] = []
|
||||
i += 1
|
||||
while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(" ") or frontmatter_lines[i].startswith("\t")):
|
||||
continuation_lines.append(frontmatter_lines[i].strip())
|
||||
i += 1
|
||||
description = " ".join(continuation_lines)
|
||||
continue
|
||||
else:
|
||||
description = value.strip('"').strip("'")
|
||||
i += 1
|
||||
|
||||
return name, description, content
|
||||
154
1-Vue3-Dev/.agents/skills/vue-best-practices/SKILL.md
Normal file
154
1-Vue3-Dev/.agents/skills/vue-best-practices/SKILL.md
Normal file
@@ -0,0 +1,154 @@
|
||||
---
|
||||
name: vue-best-practices
|
||||
description: MUST be used for Vue.js tasks. Strongly recommends Composition API with `<script setup>` and TypeScript as the standard approach. Covers Vue 3, SSR, Volar, vue-tsc. Load for any Vue, .vue files, Vue Router, Pinia, or Vite with Vue work. ALWAYS use Composition API unless the project explicitly requires Options API.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: github.com/vuejs-ai
|
||||
version: "18.0.0"
|
||||
---
|
||||
|
||||
# Vue Best Practices Workflow
|
||||
|
||||
Use this skill as an instruction set. Follow the workflow in order unless the user explicitly asks for a different order.
|
||||
|
||||
## Core Principles
|
||||
- **Keep state predictable:** one source of truth, derive everything else.
|
||||
- **Make data flow explicit:** Props down, Events up for most cases.
|
||||
- **Favor small, focused components:** easier to test, reuse, and maintain.
|
||||
- **Avoid unnecessary re-renders:** use computed properties and watchers wisely.
|
||||
- **Readability counts:** write clear, self-documenting code.
|
||||
|
||||
## 1) Confirm architecture before coding (required)
|
||||
|
||||
- Default stack: Vue 3 + Composition API + `<script setup lang="ts">`.
|
||||
- If the project explicitly uses Options API, load `vue-options-api-best-practices` skill if available.
|
||||
- If the project explicitly uses JSX, load `vue-jsx-best-practices` skill if available.
|
||||
|
||||
### 1.1 Must-read core references (required)
|
||||
|
||||
- Before implementing any Vue task, make sure to read and apply these core references:
|
||||
- `references/reactivity.md`
|
||||
- `references/sfc.md`
|
||||
- `references/component-data-flow.md`
|
||||
- `references/composables.md`
|
||||
- Keep these references in active working context for the entire task, not only when a specific issue appears.
|
||||
|
||||
### 1.2 Plan component boundaries before coding (required)
|
||||
|
||||
Create a brief component map before implementation for any non-trivial feature.
|
||||
|
||||
- Define each component's single responsibility in one sentence.
|
||||
- Keep entry/root and route-level view components as composition surfaces by default.
|
||||
- Move feature UI and feature logic out of entry/root/view components unless the task is intentionally a tiny single-file demo.
|
||||
- Define props/emits contracts for each child component in the map.
|
||||
- Prefer a feature folder layout (`components/<feature>/...`, `composables/use<Feature>.ts`) when adding more than one component.
|
||||
|
||||
## 2) Apply essential Vue foundations (required)
|
||||
|
||||
These are essential, must-know foundations. Apply all of them in every Vue task using the core references already loaded in section `1.1`.
|
||||
|
||||
### Reactivity
|
||||
|
||||
- Must-read reference from `1.1`: [reactivity](references/reactivity.md)
|
||||
- Keep source state minimal (`ref`/`reactive`), derive everything possible with `computed`.
|
||||
- Use watchers for side effects if needed.
|
||||
- Avoid recomputing expensive logic in templates.
|
||||
|
||||
### SFC structure and template safety
|
||||
|
||||
- Must-read reference from `1.1`: [sfc](references/sfc.md)
|
||||
- Keep SFC sections in this order: `<script>` → `<template>` → `<style>`.
|
||||
- Keep SFC responsibilities focused; split large components.
|
||||
- Keep templates declarative; move branching/derivation to script.
|
||||
- Apply Vue template safety rules (`v-html`, list rendering, conditional rendering choices).
|
||||
|
||||
### Keep components focused
|
||||
|
||||
Split a component when it has **more than one clear responsibility** (e.g. data orchestration + UI, or multiple independent UI sections).
|
||||
|
||||
- Prefer **smaller components + composables** over one “mega component”
|
||||
- Move **UI sections** into child components (props in, events out).
|
||||
- Move **state/side effects** into composables (`useXxx()`).
|
||||
|
||||
Apply objective split triggers. Split the component if **any** condition is true:
|
||||
|
||||
- It owns both orchestration/state and substantial presentational markup for multiple sections.
|
||||
- It has 3+ distinct UI sections (for example: form, filters, list, footer/status).
|
||||
- A template block is repeated or could become reusable (item rows, cards, list entries).
|
||||
|
||||
Entry/root and route view rule:
|
||||
|
||||
- Keep entry/root and route view components thin: app shell/layout, provider wiring, and feature composition.
|
||||
- Do not place full feature implementations in entry/root/view components when those features contain independent parts.
|
||||
- For CRUD/list features (todo, table, catalog, inbox), split at least into:
|
||||
- feature container component
|
||||
- input/form component
|
||||
- list (and/or item) component
|
||||
- footer/actions or filter/status component
|
||||
- Allow a single-file implementation only for very small throwaway demos; if chosen, explicitly justify why splitting is unnecessary.
|
||||
|
||||
### Component data flow
|
||||
|
||||
- Must-read reference from `1.1`: [component-data-flow](references/component-data-flow.md)
|
||||
- Use props down, events up as the primary model.
|
||||
- Use `v-model` only for true two-way component contracts.
|
||||
- Use provide/inject only for deep-tree dependencies or shared context.
|
||||
- Keep contracts explicit and typed with `defineProps`, `defineEmits`, and `InjectionKey` as needed.
|
||||
|
||||
### Composables
|
||||
|
||||
- Must-read reference from `1.1`: [composables](references/composables.md)
|
||||
- Extract logic into composables when it is reused, stateful, or side-effect heavy.
|
||||
- Keep composable APIs small, typed, and predictable.
|
||||
- Separate feature logic from presentational components.
|
||||
|
||||
## 3) Consider optional features only when requirements call for them
|
||||
|
||||
### 3.1 Standard optional features
|
||||
|
||||
Do not add these by default. Load the matching reference only when the requirement exists.
|
||||
|
||||
- Slots: parent needs to control child content/layout -> [component-slots](references/component-slots.md)
|
||||
- Fallthrough attributes: wrapper/base components must forward attrs/events safely -> [component-fallthrough-attrs](references/component-fallthrough-attrs.md)
|
||||
- Built-in component `<KeepAlive>` for stateful view caching -> [component-keep-alive](references/component-keep-alive.md)
|
||||
- Built-in component `<Teleport>` for overlays/portals -> [component-teleport](references/component-teleport.md)
|
||||
- Built-in component `<Suspense>` for async subtree fallback boundaries -> [component-suspense](references/component-suspense.md)
|
||||
- Animation-related features: pick the simplest approach that matches the required motion behavior.
|
||||
- Built-in component `<Transition>` for enter/leave effects -> [transition](references/component-transition.md)
|
||||
- Built-in component `<TransitionGroup>` for animated list mutations -> [transition-group](references/component-transition-group.md)
|
||||
- Class-based animation for non-enter/leave effects -> [animation-class-based-technique](references/animation-class-based-technique.md)
|
||||
- State-driven animation for user-input-driven animation -> [animation-state-driven-technique](references/animation-state-driven-technique.md)
|
||||
|
||||
### 3.2 Less-common optional features
|
||||
|
||||
Use these only when there is explicit product or technical need.
|
||||
|
||||
- Directives: behavior is DOM-specific and not a good composable/component fit -> [directives](references/directives.md)
|
||||
- Async components: heavy/rarely-used UI should be lazy loaded -> [component-async](references/component-async.md)
|
||||
- Render functions only when templates cannot express the requirement -> [render-functions](references/render-functions.md)
|
||||
- Plugins when behavior must be installed app-wide -> [plugins](references/plugins.md)
|
||||
- State management patterns: app-wide shared state crosses feature boundaries -> [state-management](references/state-management.md)
|
||||
|
||||
## 4) Run performance optimization after behavior is correct
|
||||
|
||||
Performance work is a post-functionality pass. Do not optimize before core behavior is implemented and verified.
|
||||
|
||||
- Large list rendering bottlenecks -> [perf-virtualize-large-lists](references/perf-virtualize-large-lists.md)
|
||||
- Static subtrees re-rendering unnecessarily -> [perf-v-once-v-memo-directives](references/perf-v-once-v-memo-directives.md)
|
||||
- Over-abstraction in hot list paths -> [perf-avoid-component-abstraction-in-lists](references/perf-avoid-component-abstraction-in-lists.md)
|
||||
- Expensive updates triggered too often -> [updated-hook-performance](references/updated-hook-performance.md)
|
||||
|
||||
## 5) Final self-check before finishing
|
||||
|
||||
- Core behavior works and matches requirements.
|
||||
- All must-read references were read and applied.
|
||||
- Reactivity model is minimal and predictable.
|
||||
- SFC structure and template rules are followed.
|
||||
- Components are focused and well-factored, splitting when needed.
|
||||
- Entry/root and route view components remain composition surfaces unless there is an explicit small-demo exception.
|
||||
- Component split decisions are explicit and defensible (responsibility boundaries are clear).
|
||||
- Data flow contracts are explicit and typed.
|
||||
- Composables are used where reuse/complexity justifies them.
|
||||
- Moved state/side effects into composables if applicable
|
||||
- Optional features are used only when requirements demand them.
|
||||
- Performance changes were applied only after functionality was complete.
|
||||
@@ -0,0 +1,254 @@
|
||||
---
|
||||
title: Use Class-based Animations for Non-Enter/Leave Effects
|
||||
impact: LOW
|
||||
impactDescription: Class-based animations are simpler and more performant for elements that remain in the DOM
|
||||
type: best-practice
|
||||
tags: [vue3, animation, css, class-binding, state]
|
||||
---
|
||||
|
||||
# Use Class-based Animations for Non-Enter/Leave Effects
|
||||
|
||||
**Impact: LOW** - For animations on elements that are not entering or leaving the DOM, use CSS class-based animations triggered by Vue's reactive state. This is simpler than `<Transition>` and more appropriate for feedback animations like shake, pulse, or highlight effects.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use class-based animations for elements staying in the DOM
|
||||
- Use `<Transition>` only for enter/leave animations
|
||||
- Combine CSS animations with Vue's class bindings (`:class`)
|
||||
- Consider using `setTimeout` to auto-remove animation classes
|
||||
|
||||
**When to Use Class-based Animations:**
|
||||
- User feedback (shake on error, pulse on success)
|
||||
- Attention-grabbing effects (highlight changes)
|
||||
- Hover/focus states that need more than CSS transitions
|
||||
- Any animation where the element stays mounted
|
||||
|
||||
**When to Use Transition Component:**
|
||||
- Elements entering/leaving the DOM (v-if/v-show)
|
||||
- Route transitions
|
||||
- List item additions/removals
|
||||
|
||||
## Basic Pattern
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div :class="{ shake: showError }">
|
||||
<button @click="submitForm">Submit</button>
|
||||
<span v-if="showError">This feature is disabled!</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const showError = ref(false)
|
||||
|
||||
function submitForm() {
|
||||
if (!isValid()) {
|
||||
// Trigger shake animation
|
||||
showError.value = true
|
||||
|
||||
// Auto-remove class after animation completes
|
||||
setTimeout(() => {
|
||||
showError.value = false
|
||||
}, 820) // Match animation duration
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.shake {
|
||||
animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
|
||||
transform: translate3d(0, 0, 0); /* Enable GPU acceleration */
|
||||
}
|
||||
|
||||
@keyframes shake {
|
||||
10%, 90% { transform: translate3d(-1px, 0, 0); }
|
||||
20%, 80% { transform: translate3d(2px, 0, 0); }
|
||||
30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
|
||||
40%, 60% { transform: translate3d(4px, 0, 0); }
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Common Animation Patterns
|
||||
|
||||
### Pulse on Success
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<button
|
||||
@click="save"
|
||||
:class="{ pulse: saved }"
|
||||
>
|
||||
{{ saved ? 'Saved!' : 'Save' }}
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const saved = ref(false)
|
||||
|
||||
async function save() {
|
||||
await saveData()
|
||||
saved.value = true
|
||||
setTimeout(() => saved.value = false, 1000)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.pulse {
|
||||
animation: pulse 0.5s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { transform: scale(1); }
|
||||
50% { transform: scale(1.05); }
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Highlight on Change
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
:class="{ highlight: justUpdated }"
|
||||
>
|
||||
Value: {{ value }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
const value = ref(0)
|
||||
const justUpdated = ref(false)
|
||||
|
||||
watch(value, () => {
|
||||
justUpdated.value = true
|
||||
setTimeout(() => justUpdated.value = false, 1000)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.highlight {
|
||||
animation: highlight 1s ease-out;
|
||||
}
|
||||
|
||||
@keyframes highlight {
|
||||
0% { background-color: yellow; }
|
||||
100% { background-color: transparent; }
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Bounce Attention
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
:class="{ bounce: needsAttention }"
|
||||
@animationend="needsAttention = false"
|
||||
>
|
||||
<BellIcon />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const needsAttention = ref(false)
|
||||
|
||||
function notifyUser() {
|
||||
needsAttention.value = true
|
||||
// No setTimeout needed - using animationend event
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.bounce {
|
||||
animation: bounce 0.5s ease;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-10px); }
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Using animationend Event
|
||||
|
||||
Instead of `setTimeout`, use the `animationend` event for cleaner code:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
:class="{ animate: isAnimating }"
|
||||
@animationend="isAnimating = false"
|
||||
>
|
||||
Content
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const isAnimating = ref(false)
|
||||
|
||||
function triggerAnimation() {
|
||||
isAnimating.value = true
|
||||
// Class is automatically removed when animation ends
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Composable for Reusable Animations
|
||||
|
||||
```javascript
|
||||
// composables/useAnimation.js
|
||||
import { ref } from 'vue'
|
||||
|
||||
export function useAnimation(duration = 500) {
|
||||
const isAnimating = ref(false)
|
||||
|
||||
function trigger() {
|
||||
isAnimating.value = true
|
||||
setTimeout(() => {
|
||||
isAnimating.value = false
|
||||
}, duration)
|
||||
}
|
||||
|
||||
return {
|
||||
isAnimating,
|
||||
trigger
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useAnimation } from '@/composables/useAnimation'
|
||||
|
||||
const shake = useAnimation(820)
|
||||
const pulse = useAnimation(500)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
:class="{ shake: shake.isAnimating.value }"
|
||||
@click="shake.trigger()"
|
||||
>
|
||||
Shake me
|
||||
</button>
|
||||
|
||||
<button
|
||||
:class="{ pulse: pulse.isAnimating.value }"
|
||||
@click="pulse.trigger()"
|
||||
>
|
||||
Pulse me
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
@@ -0,0 +1,291 @@
|
||||
---
|
||||
title: State-driven Animations with CSS Transitions and Style Bindings
|
||||
impact: LOW
|
||||
impactDescription: Combining Vue's reactive style bindings with CSS transitions creates smooth, interactive animations
|
||||
type: best-practice
|
||||
tags: [vue3, animation, css, transition, style-binding, state, interactive]
|
||||
---
|
||||
|
||||
# State-driven Animations with CSS Transitions and Style Bindings
|
||||
|
||||
**Impact: LOW** - For responsive, interactive animations that react to user input or state changes, combine Vue's dynamic style bindings with CSS transitions. This creates smooth animations that interpolate values in real-time based on state.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use `:style` binding for dynamic properties that change frequently
|
||||
- Add CSS `transition` property to smoothly animate between values
|
||||
- Consider using `transform` and `opacity` for GPU-accelerated animations
|
||||
- For complex value interpolation, use watchers with animation libraries
|
||||
|
||||
## Basic Pattern
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
@mousemove="onMousemove"
|
||||
:style="{ backgroundColor: `hsl(${hue}, 80%, 50%)` }"
|
||||
class="interactive-area"
|
||||
>
|
||||
<p>Move your mouse across this div...</p>
|
||||
<p>Hue: {{ hue }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const hue = ref(0)
|
||||
|
||||
function onMousemove(e) {
|
||||
// Map mouse X position to hue (0-360)
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
hue.value = Math.round((e.clientX - rect.left) / rect.width * 360)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.interactive-area {
|
||||
transition: background-color 0.3s ease;
|
||||
height: 200px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Following Mouse Position
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
class="container"
|
||||
@mousemove="onMousemove"
|
||||
>
|
||||
<div
|
||||
class="follower"
|
||||
:style="{
|
||||
transform: `translate(${x}px, ${y}px)`
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
function onMousemove(e) {
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
x.value = e.clientX - rect.left
|
||||
y.value = e.clientY - rect.top
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.container {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.follower {
|
||||
position: absolute;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
background: blue;
|
||||
border-radius: 50%;
|
||||
/* Smooth following with transition */
|
||||
transition: transform 0.1s ease-out;
|
||||
/* Prevent the follower from triggering mousemove */
|
||||
pointer-events: none;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Progress Animation
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="progress-container">
|
||||
<div
|
||||
class="progress-bar"
|
||||
:style="{ width: `${progress}%` }"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
v-model.number="progress"
|
||||
min="0"
|
||||
max="100"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const progress = ref(0)
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.progress-container {
|
||||
height: 20px;
|
||||
background: #e0e0e0;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #4CAF50, #8BC34A);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Scroll-based Animation
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
class="hero"
|
||||
:style="{
|
||||
opacity: heroOpacity,
|
||||
transform: `translateY(${scrollOffset}px)`
|
||||
}"
|
||||
>
|
||||
<h1>Scroll Down</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
const scrollY = ref(0)
|
||||
|
||||
const heroOpacity = computed(() => {
|
||||
return Math.max(0, 1 - scrollY.value / 300)
|
||||
})
|
||||
|
||||
const scrollOffset = computed(() => {
|
||||
return scrollY.value * 0.5 // Parallax effect
|
||||
})
|
||||
|
||||
function handleScroll() {
|
||||
scrollY.value = window.scrollY
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('scroll', handleScroll, { passive: true })
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('scroll', handleScroll)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.hero {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
/* Note: No transition for scroll-based animations - they should be instant */
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Color Theme Transition
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div
|
||||
class="app"
|
||||
:style="themeStyles"
|
||||
>
|
||||
<button @click="toggleTheme">Toggle Theme</button>
|
||||
<p>Current theme: {{ isDark ? 'Dark' : 'Light' }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const isDark = ref(false)
|
||||
|
||||
const themeStyles = computed(() => ({
|
||||
'--bg-color': isDark.value ? '#1a1a1a' : '#ffffff',
|
||||
'--text-color': isDark.value ? '#ffffff' : '#1a1a1a',
|
||||
backgroundColor: 'var(--bg-color)',
|
||||
color: 'var(--text-color)'
|
||||
}))
|
||||
|
||||
function toggleTheme() {
|
||||
isDark.value = !isDark.value
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.app {
|
||||
min-height: 100vh;
|
||||
transition: background-color 0.5s ease, color 0.5s ease;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Advanced: Numerical Tweening with Watchers
|
||||
|
||||
For smooth number animations (counters, stats), use watchers with animation libraries:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<input v-model.number="targetNumber" type="number" />
|
||||
<p class="counter">{{ displayNumber.toFixed(0) }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, reactive, watch } from 'vue'
|
||||
import gsap from 'gsap'
|
||||
|
||||
const targetNumber = ref(0)
|
||||
const tweened = reactive({ value: 0 })
|
||||
|
||||
// Computed for display
|
||||
const displayNumber = computed(() => tweened.value)
|
||||
|
||||
watch(targetNumber, (newValue) => {
|
||||
gsap.to(tweened, {
|
||||
duration: 0.5,
|
||||
value: Number(newValue) || 0,
|
||||
ease: 'power2.out'
|
||||
})
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
```vue
|
||||
<style>
|
||||
/* GOOD: GPU-accelerated properties */
|
||||
.element {
|
||||
transition: transform 0.3s ease, opacity 0.3s ease;
|
||||
}
|
||||
|
||||
/* AVOID: Properties that trigger layout recalculation */
|
||||
.element {
|
||||
transition: width 0.3s ease, height 0.3s ease, margin 0.3s ease;
|
||||
}
|
||||
|
||||
/* For high-frequency updates, consider will-change */
|
||||
.frequently-animated {
|
||||
will-change: transform;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: Async Component Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Poor async component strategy can delay interactivity in SSR apps and create loading UI flicker
|
||||
type: best-practice
|
||||
tags: [vue3, async-components, ssr, hydration, performance, ux]
|
||||
---
|
||||
|
||||
# Async Component Best Practices
|
||||
|
||||
**Impact: MEDIUM** - Async components should reduce JavaScript cost without degrading perceived performance. Focus on hydration timing in SSR and stable loading UX.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use lazy hydration strategies for non-critical SSR component trees
|
||||
- Import only the hydration helpers you actually use
|
||||
- Keep `loadingComponent` delay near the default `200ms` unless real UX data suggests otherwise
|
||||
- Configure `delay` and `timeout` together for predictable loading behavior
|
||||
|
||||
## Use Lazy Hydration Strategies in SSR
|
||||
|
||||
In Vue 3.5+, async components can delay hydration until idle time, visibility, media query match, or user interaction.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
const AsyncComments = defineAsyncComponent({
|
||||
loader: () => import('./Comments.vue')
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
defineAsyncComponent,
|
||||
hydrateOnVisible,
|
||||
hydrateOnIdle
|
||||
} from 'vue'
|
||||
|
||||
const AsyncComments = defineAsyncComponent({
|
||||
loader: () => import('./Comments.vue'),
|
||||
hydrate: hydrateOnVisible({ rootMargin: '100px' })
|
||||
})
|
||||
|
||||
const AsyncFooter = defineAsyncComponent({
|
||||
loader: () => import('./Footer.vue'),
|
||||
hydrate: hydrateOnIdle(5000)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Prevent Loading Spinner Flicker
|
||||
|
||||
Avoid showing loading UI immediately for components that usually resolve quickly.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import LoadingSpinner from './LoadingSpinner.vue'
|
||||
|
||||
const AsyncDashboard = defineAsyncComponent({
|
||||
loader: () => import('./Dashboard.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
delay: 0
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import LoadingSpinner from './LoadingSpinner.vue'
|
||||
import ErrorDisplay from './ErrorDisplay.vue'
|
||||
|
||||
const AsyncDashboard = defineAsyncComponent({
|
||||
loader: () => import('./Dashboard.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
errorComponent: ErrorDisplay,
|
||||
delay: 200,
|
||||
timeout: 30000
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Delay Guidelines
|
||||
|
||||
| Scenario | Recommended Delay |
|
||||
|----------|-------------------|
|
||||
| Small component, fast network | `200ms` |
|
||||
| Known heavy component | `100ms` |
|
||||
| Background or non-critical UI | `300-500ms` |
|
||||
@@ -0,0 +1,307 @@
|
||||
---
|
||||
title: Component Data Flow Best Practices
|
||||
impact: HIGH
|
||||
impactDescription: Clear data flow between components prevents state bugs, stale UI, and brittle coupling
|
||||
type: best-practice
|
||||
tags: [vue3, props, emits, v-model, provide-inject, data-flow, typescript]
|
||||
---
|
||||
|
||||
# Component Data Flow Best Practices
|
||||
|
||||
**Impact: HIGH** - Vue components stay reliable when data flow is explicit: props go down, events go up, `v-model` handles two-way bindings, and provide/inject supports cross-tree dependencies. Blurring these boundaries leads to stale state, hidden coupling, and hard-to-debug UI.
|
||||
|
||||
The main principle of data flow in Vue.js is **Props Down / Events Up**. This is the most maintainable default, and one-way flow scales well.
|
||||
|
||||
## Task List
|
||||
|
||||
- Treat props as read-only inputs
|
||||
- Use props/emit for component communication; reserve refs for imperative actions
|
||||
- When refs are required for imperative APIs, type them with template refs
|
||||
- Emit events instead of mutating parent state directly
|
||||
- Use `defineModel` for v-model in modern Vue (3.4+)
|
||||
- Handle v-model modifiers deliberately in child components
|
||||
- Use symbols for provide/inject keys to avoid props drilling (over ~3 layers)
|
||||
- Keep mutations in the provider or expose explicit actions
|
||||
- In TypeScript projects, prefer type-based `defineProps`, `defineEmits`, and `InjectionKey`
|
||||
|
||||
## Props: One-Way Data Down
|
||||
|
||||
Props are inputs. Do not mutate them in the child.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
const props = defineProps({ count: Number })
|
||||
|
||||
function increment() {
|
||||
props.count++
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
If state needs to change, emit an event, use `v-model` or create a local copy.
|
||||
|
||||
## Prefer props/emit over component refs
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import UserForm from './UserForm.vue'
|
||||
|
||||
const formRef = ref(null)
|
||||
|
||||
function submitForm() {
|
||||
if (formRef.value.isValid) {
|
||||
formRef.value.submit()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UserForm ref="formRef" />
|
||||
<button @click="submitForm">Submit</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import UserForm from './UserForm.vue'
|
||||
|
||||
function handleSubmit(formData) {
|
||||
api.submit(formData)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UserForm @submit="handleSubmit" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Type component refs when imperative access is required
|
||||
|
||||
Prefer props/emits by default. When a parent must call an exposed child method, type the ref explicitly and expose only the intended API from the child with `defineExpose`.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import DialogPanel from './DialogPanel.vue'
|
||||
|
||||
const panelRef = ref(null)
|
||||
|
||||
onMounted(() => {
|
||||
panelRef.value.open()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogPanel ref="panelRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- DialogPanel.vue -->
|
||||
<script setup lang="ts">
|
||||
function open() {}
|
||||
|
||||
defineExpose({ open })
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, useTemplateRef } from 'vue'
|
||||
import DialogPanel from './DialogPanel.vue'
|
||||
|
||||
// Vue 3.5+ with useTemplateRef
|
||||
const panelRef = useTemplateRef('panelRef')
|
||||
|
||||
// Before Vue 3.5 with manual typing and ref
|
||||
// const panelRef = ref<InstanceType<typeof DialogPanel> | null>(null)
|
||||
|
||||
onMounted(() => {
|
||||
panelRef.value?.open()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogPanel ref="panelRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Emits: Explicit Events Up
|
||||
|
||||
Component events do not bubble. If a parent needs to know about an event, re-emit it explicitly.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<!-- Parent expects "saved" from grandchild, but it won't bubble -->
|
||||
<Child @saved="onSaved" />
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- Child.vue -->
|
||||
<script setup>
|
||||
const emit = defineEmits(['saved'])
|
||||
|
||||
function onGrandchildSaved(payload) {
|
||||
emit('saved', payload)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Grandchild @saved="onGrandchildSaved" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**Event naming:** use kebab-case in templates and camelCase in script:
|
||||
```vue
|
||||
<script setup>
|
||||
const emit = defineEmits(['updateUser'])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ProfileForm @update-user="emit('updateUser', $event)" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## `v-model`: Predictable Two-Way Bindings
|
||||
|
||||
Use `defineModel` by default for component bindings and emit updates on input. Only use the `modelValue` + `update:modelValue` pattern if you are on Vue < 3.4.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
const props = defineProps({ value: String })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input :value="props.value" @input="$emit('input', $event.target.value)" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD (Vue 3.4+):**
|
||||
```vue
|
||||
<script setup>
|
||||
const model = defineModel({ type: String })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="model" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD (Vue < 3.4):**
|
||||
```vue
|
||||
<script setup>
|
||||
const props = defineProps({ modelValue: String })
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input
|
||||
:value="props.modelValue"
|
||||
@input="emit('update:modelValue', $event.target.value)"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
If you need the updated value immediately after a change, use the input event value or `nextTick` in the parent.
|
||||
|
||||
## Provide/Inject: Shared Context Without Prop Drilling
|
||||
|
||||
Use provide/inject for cross-tree state, but keep mutations centralized in the provider and expose explicit actions.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
// Provider.vue
|
||||
provide('theme', reactive({ dark: false }))
|
||||
|
||||
// Consumer.vue
|
||||
const theme = inject('theme')
|
||||
// Mutating shared state from any depth becomes hard to track
|
||||
theme.dark = true
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
// Provider.vue
|
||||
const theme = reactive({ dark: false })
|
||||
const toggleTheme = () => { theme.dark = !theme.dark }
|
||||
|
||||
provide(themeKey, readonly(theme))
|
||||
provide(themeActionsKey, { toggleTheme })
|
||||
|
||||
// Consumer.vue
|
||||
const theme = inject(themeKey)
|
||||
const { toggleTheme } = inject(themeActionsKey)
|
||||
```
|
||||
|
||||
Use symbols for keys to avoid collisions in large apps:
|
||||
```ts
|
||||
export const themeKey = Symbol('theme')
|
||||
export const themeActionsKey = Symbol('theme-actions')
|
||||
```
|
||||
|
||||
## Use TypeScript Contracts for Public Component APIs
|
||||
|
||||
In TypeScript projects, type component boundaries directly with `defineProps`, `defineEmits`, and `InjectionKey` so invalid payloads and mismatched injections fail at compile time.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
userId: String
|
||||
})
|
||||
|
||||
const emit = defineEmits(['save'])
|
||||
const settings = inject('settings')
|
||||
|
||||
// Payload shape is not checked here
|
||||
emit('save', 123)
|
||||
|
||||
// Key is string-based and not type-safe
|
||||
settings?.theme = 'dark'
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { inject, provide } from 'vue'
|
||||
import type { InjectionKey } from 'vue'
|
||||
|
||||
interface Props {
|
||||
userId: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
save: [payload: { id: string; draft: boolean }]
|
||||
}
|
||||
|
||||
interface Settings {
|
||||
theme: 'light' | 'dark'
|
||||
}
|
||||
|
||||
const settingsKey: InjectionKey<Settings> = Symbol('settings')
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
provide(settingsKey, { theme: 'light' })
|
||||
|
||||
const settings = inject(settingsKey)
|
||||
if (settings) {
|
||||
emit('save', { id: props.userId, draft: false })
|
||||
}
|
||||
</script>
|
||||
```
|
||||
@@ -0,0 +1,174 @@
|
||||
---
|
||||
title: Component Fallthrough Attributes Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Incorrect $attrs access and reactivity assumptions can cause undefined values and watchers that never run
|
||||
type: best-practice
|
||||
tags: [vue3, attrs, fallthrough-attributes, composition-api, reactivity]
|
||||
---
|
||||
|
||||
# Component Fallthrough Attributes Best Practices
|
||||
|
||||
**Impact: MEDIUM** - Fallthrough attributes are straightforward once you follow Vue's conventions: hyphenated names use bracket notation, listener keys are camelCase `onX`, and `useAttrs()` is current-but-not-reactive.
|
||||
|
||||
## Task List
|
||||
|
||||
- Access hyphenated attribute names with bracket notation (for example `attrs['data-testid']`)
|
||||
- Access event listeners with camelCase `onX` keys (for example `attrs.onClick`)
|
||||
- Do not `watch()` values returned from `useAttrs()`; those watchers do not trigger on attr changes
|
||||
- Use `onUpdated()` for attr-driven side effects
|
||||
- Promote frequently observed attrs to props when reactive observation is required
|
||||
|
||||
## Access Attribute and Listener Keys Correctly
|
||||
|
||||
Hyphenated attribute names preserve their original casing in JavaScript, so dot notation does not work for keys that include `-`.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { useAttrs } from 'vue'
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
console.log(attrs.data-testid) // Syntax error
|
||||
console.log(attrs.dataTestid) // undefined for data-testid
|
||||
console.log(attrs['on-click']) // undefined
|
||||
console.log(attrs['@click']) // undefined
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { useAttrs } from 'vue'
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
console.log(attrs['data-testid'])
|
||||
console.log(attrs['aria-label'])
|
||||
console.log(attrs['foo-bar'])
|
||||
|
||||
console.log(attrs.onClick)
|
||||
console.log(attrs.onCustomEvent)
|
||||
console.log(attrs.onMouseEnter)
|
||||
</script>
|
||||
```
|
||||
|
||||
### Naming Reference
|
||||
|
||||
| Parent Usage | Access in `attrs` |
|
||||
|--------------|-------------------|
|
||||
| `class="foo"` | `attrs.class` |
|
||||
| `data-id="123"` | `attrs['data-id']` |
|
||||
| `aria-label="..."` | `attrs['aria-label']` |
|
||||
| `foo-bar="baz"` | `attrs['foo-bar']` |
|
||||
| `@click="fn"` | `attrs.onClick` |
|
||||
| `@custom-event="fn"` | `attrs.onCustomEvent` |
|
||||
| `@update:modelValue="fn"` | `attrs['onUpdate:modelValue']` |
|
||||
|
||||
## `useAttrs()` Is Not Reactive
|
||||
|
||||
`useAttrs()` always reflects the latest values, but it is intentionally not reactive for watcher tracking.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { watch, watchEffect, useAttrs } from 'vue'
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
watch(
|
||||
() => attrs.someAttr,
|
||||
(newValue) => {
|
||||
console.log('Changed:', newValue) // Never runs on attr changes
|
||||
}
|
||||
)
|
||||
|
||||
watchEffect(() => {
|
||||
console.log(attrs.class) // Runs on setup, not on attr updates
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { onUpdated, useAttrs } from 'vue'
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
onUpdated(() => {
|
||||
console.log('Latest attrs:', attrs)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { watch } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
someAttr: String
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.someAttr,
|
||||
(newValue) => {
|
||||
console.log('Changed:', newValue)
|
||||
}
|
||||
)
|
||||
</script>
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Check for optional attrs safely
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { computed, useAttrs } from 'vue'
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
const hasTestId = computed(() => 'data-testid' in attrs)
|
||||
const ariaLabel = computed(() => attrs['aria-label'] ?? 'Default label')
|
||||
</script>
|
||||
```
|
||||
|
||||
### Forward listeners after internal logic
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useAttrs } from 'vue'
|
||||
|
||||
defineOptions({ inheritAttrs: false })
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
function handleClick(event) {
|
||||
console.log('Internal handling first')
|
||||
attrs.onClick?.(event)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleClick">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## TypeScript Notes
|
||||
|
||||
`useAttrs()` is typed as `Record<string, unknown>`, so cast individual keys when needed.
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from 'vue'
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
const testId = attrs['data-testid'] as string | undefined
|
||||
const onClick = attrs.onClick as ((event: MouseEvent) => void) | undefined
|
||||
</script>
|
||||
```
|
||||
@@ -0,0 +1,137 @@
|
||||
---
|
||||
title: KeepAlive Component Best Practices
|
||||
impact: HIGH
|
||||
impactDescription: KeepAlive caches component instances; misuse causes stale data, memory growth, or unexpected lifecycle behavior
|
||||
type: best-practice
|
||||
tags: [vue3, keepalive, cache, performance, router, dynamic-components]
|
||||
---
|
||||
|
||||
# KeepAlive Component Best Practices
|
||||
|
||||
**Impact: HIGH** - `<KeepAlive>` caches component instances instead of destroying them. Use it to preserve state across switches, but manage cache size and freshness explicitly to avoid memory growth or stale UI.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use KeepAlive only where state preservation improves UX
|
||||
- Set a reasonable `max` to cap cache size
|
||||
- Declare component names for include/exclude matching
|
||||
- Use `onActivated`/`onDeactivated` for cache-aware logic
|
||||
- Decide how and when cached views refresh their data
|
||||
- Avoid caching memory-heavy or security-sensitive views
|
||||
|
||||
## When to Use KeepAlive
|
||||
|
||||
Use KeepAlive when switching between views where state should persist (tabs, multi-step forms, dashboards). Avoid it when each visit should start fresh.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- State resets on every switch -->
|
||||
<component :is="currentTab" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- State preserved between switches -->
|
||||
<KeepAlive>
|
||||
<component :is="currentTab" />
|
||||
</KeepAlive>
|
||||
</template>
|
||||
```
|
||||
|
||||
## When NOT to Use KeepAlive
|
||||
|
||||
- Search or filter pages where users expect fresh results
|
||||
- Memory-heavy components (maps, large tables, media players)
|
||||
- Sensitive flows where data must be cleared on exit
|
||||
- Components with heavy background activity you cannot pause
|
||||
|
||||
## Limit and Control the Cache
|
||||
|
||||
Always cap cache size with `max` and restrict caching to specific components when possible.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<KeepAlive :max="5" include="Dashboard,Settings">
|
||||
<component :is="currentView" />
|
||||
</KeepAlive>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Ensure Component Names Match include/exclude
|
||||
|
||||
`include` and `exclude` match the component `name` option. Explicitly set names for reliable caching.
|
||||
|
||||
```vue
|
||||
<!-- TabA.vue -->
|
||||
<script setup>
|
||||
defineOptions({ name: 'TabA' })
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<KeepAlive include="TabA,TabB">
|
||||
<component :is="currentTab" />
|
||||
</KeepAlive>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Cache Invalidation Strategies
|
||||
|
||||
Vue 3 has no direct API to remove a specific cached instance. Use keys or dynamic include/exclude to force refreshes.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
const currentView = ref('Dashboard')
|
||||
const viewKeys = reactive({ Dashboard: 0, Settings: 0 })
|
||||
|
||||
function invalidateCache(view) {
|
||||
viewKeys[view]++
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<KeepAlive>
|
||||
<component :is="currentView" :key="`${currentView}-${viewKeys[currentView]}`" />
|
||||
</KeepAlive>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Lifecycle Hooks for Cached Components
|
||||
|
||||
Cached components are not destroyed on switch. Use activation hooks for refresh and cleanup.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { onActivated, onDeactivated } from 'vue'
|
||||
|
||||
onActivated(() => {
|
||||
refreshData()
|
||||
})
|
||||
|
||||
onDeactivated(() => {
|
||||
pauseTimers()
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Router Caching and Freshness
|
||||
|
||||
Decide whether navigation should show cached state or a fresh view. A common pattern is to key by route when params change.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<router-view v-slot="{ Component, route }">
|
||||
<KeepAlive>
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</KeepAlive>
|
||||
</router-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
If you want cache reuse but fresh data, refresh in `onActivated` and compare query/params before fetching.
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
title: Component Slots Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Poor slot API design causes empty DOM wrappers, weak TypeScript safety, brittle defaults, and unnecessary component overhead
|
||||
type: best-practice
|
||||
tags: [vue3, slots, components, typescript, composables]
|
||||
---
|
||||
|
||||
# Component Slots Best Practices
|
||||
|
||||
**Impact: MEDIUM** - Slots are a core component API surface in Vue. Structure them intentionally so templates stay predictable, typed, and performant.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use shorthand syntax for named slots (`#` instead of `v-slot:`)
|
||||
- Render optional slot wrapper elements only when slot content exists (`$slots` checks)
|
||||
- Type scoped slot contracts with `defineSlots` in TypeScript components
|
||||
- Provide fallback content for optional slots
|
||||
- Prefer composables over renderless components for pure logic reuse
|
||||
|
||||
## Shorthand syntax for named slots
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<MyComponent>
|
||||
<template v-slot:header> ... </template>
|
||||
</MyComponent>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<MyComponent>
|
||||
<template #header> ... </template>
|
||||
</MyComponent>
|
||||
```
|
||||
|
||||
## Conditionally Render Optional Slot Wrappers
|
||||
|
||||
Use `$slots` checks when wrapper elements add spacing, borders, or layout constraints.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<!-- Card.vue -->
|
||||
<template>
|
||||
<article class="card">
|
||||
<header class="card-header">
|
||||
<slot name="header" />
|
||||
</header>
|
||||
|
||||
<section class="card-body">
|
||||
<slot />
|
||||
</section>
|
||||
|
||||
<footer class="card-footer">
|
||||
<slot name="footer" />
|
||||
</footer>
|
||||
</article>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- Card.vue -->
|
||||
<template>
|
||||
<article class="card">
|
||||
<header v-if="$slots.header" class="card-header">
|
||||
<slot name="header" />
|
||||
</header>
|
||||
|
||||
<section v-if="$slots.default" class="card-body">
|
||||
<slot />
|
||||
</section>
|
||||
|
||||
<footer v-if="$slots.footer" class="card-footer">
|
||||
<slot name="footer" />
|
||||
</footer>
|
||||
</article>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Type Scoped Slot Props with defineSlots
|
||||
|
||||
In `<script setup lang="ts">`, use `defineSlots` so slot consumers get autocomplete and static checks.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<!-- ProductList.vue -->
|
||||
<script setup lang="ts">
|
||||
interface Product {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
defineProps<{ products: Product[] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul>
|
||||
<li v-for="(product, index) in products" :key="product.id">
|
||||
<slot :product="product" :index="index" />
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- ProductList.vue -->
|
||||
<script setup lang="ts">
|
||||
interface Product {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
defineProps<{ products: Product[] }>()
|
||||
|
||||
defineSlots<{
|
||||
default(props: { product: Product; index: number }): any
|
||||
empty(): any
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul v-if="products.length">
|
||||
<li v-for="(product, index) in products" :key="product.id">
|
||||
<slot :product="product" :index="index" />
|
||||
</li>
|
||||
</ul>
|
||||
<slot v-else name="empty" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Provide Slot Fallback Content
|
||||
|
||||
Fallback content makes components resilient when parents omit optional slots.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<!-- SubmitButton.vue -->
|
||||
<template>
|
||||
<button type="submit" class="btn-primary">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- SubmitButton.vue -->
|
||||
<template>
|
||||
<button type="submit" class="btn-primary">
|
||||
<slot>Submit</slot>
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Prefer Composables for Pure Logic Reuse
|
||||
|
||||
Renderless components are still useful for slot-driven composition, but composables are usually cleaner for logic-only reuse.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<!-- MouseTracker.vue -->
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
function onMove(event: MouseEvent) {
|
||||
x.value = event.pageX
|
||||
y.value = event.pageY
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('mousemove', onMove))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', onMove))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<slot :x="x" :y="y" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
// composables/useMouse.ts
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
export function useMouse() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
function onMove(event: MouseEvent) {
|
||||
x.value = event.pageX
|
||||
y.value = event.pageY
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('mousemove', onMove))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', onMove))
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- MousePosition.vue -->
|
||||
<script setup lang="ts">
|
||||
import { useMouse } from '@/composables/useMouse'
|
||||
|
||||
const { x, y } = useMouse()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p>{{ x }}, {{ y }}</p>
|
||||
</template>
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
title: Suspense Component Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Suspense coordinates async dependencies with fallback UI; misconfiguration leads to missing loading states or confusing UX
|
||||
type: best-practice
|
||||
tags: [vue3, suspense, async-components, async-setup, loading, fallback, router, transition, keepalive]
|
||||
---
|
||||
|
||||
# Suspense Component Best Practices
|
||||
|
||||
**Impact: MEDIUM** - `<Suspense>` coordinates async dependencies (async components or async setup) and renders a fallback while they resolve. Misconfiguration leads to missing loading states, empty renders, or subtle UX bugs.
|
||||
|
||||
## Task List
|
||||
|
||||
- Wrap default and fallback slot content in a single root node
|
||||
- Use `timeout` when you need the fallback to appear on reverts
|
||||
- Force root replacement with `:key` when you need Suspense to re-trigger
|
||||
- Add `suspensible` to nested Suspense boundaries (Vue 3.3+)
|
||||
- Use `@pending`, `@resolve`, and `@fallback` for programmatic loading state
|
||||
- Nest `RouterView` -> `Transition` -> `KeepAlive` -> `Suspense` in that order
|
||||
- Keep Suspense usage centralized and documented in production
|
||||
|
||||
## Single Root in Default and Fallback Slots
|
||||
|
||||
Suspense tracks a single immediate child in both slots. Wrap multiple elements in a single element or component.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<AsyncHeader />
|
||||
<AsyncList />
|
||||
|
||||
<template #fallback>
|
||||
<LoadingSpinner />
|
||||
<LoadingHint />
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<div>
|
||||
<AsyncHeader />
|
||||
<AsyncList />
|
||||
</div>
|
||||
|
||||
<template #fallback>
|
||||
<div>
|
||||
<LoadingSpinner />
|
||||
<LoadingHint />
|
||||
</div>
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Fallback Timing on Reverts (`timeout`)
|
||||
|
||||
When Suspense is already resolved and new async work starts, the previous content remains visible until the timeout elapses. Use `timeout="0"` for immediate fallback or a short delay to avoid flicker.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<component :is="currentView" :key="viewKey" />
|
||||
|
||||
<template #fallback>
|
||||
Loading...
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense :timeout="200">
|
||||
<component :is="currentView" :key="viewKey" />
|
||||
|
||||
<template #fallback>
|
||||
Loading...
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Pending State Only Re-triggers on Root Replacement
|
||||
|
||||
Once resolved, Suspense only re-enters pending when the root node of the default slot changes. If async work happens deeper in the tree, no fallback appears.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<TabContainer>
|
||||
<AsyncDashboard v-if="tab === 'dashboard'" />
|
||||
<AsyncSettings v-else />
|
||||
</TabContainer>
|
||||
|
||||
<template #fallback>
|
||||
Loading...
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<component :is="tabs[tab]" :key="tab" />
|
||||
|
||||
<template #fallback>
|
||||
Loading...
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Use `suspensible` for Nested Suspense (Vue 3.3+)
|
||||
|
||||
Nested Suspense boundaries need `suspensible` on the inner boundary so the parent can coordinate loading state. Without it, inner async content may render empty nodes until resolved.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<LayoutShell>
|
||||
<Suspense>
|
||||
<AsyncWidget />
|
||||
<template #fallback>Loading widget...</template>
|
||||
</Suspense>
|
||||
</LayoutShell>
|
||||
|
||||
<template #fallback>Loading layout...</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<LayoutShell>
|
||||
<Suspense suspensible>
|
||||
<AsyncWidget />
|
||||
<template #fallback>Loading widget...</template>
|
||||
</Suspense>
|
||||
</LayoutShell>
|
||||
|
||||
<template #fallback>Loading layout...</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Track Loading with Suspense Events
|
||||
|
||||
Use `@pending`, `@resolve`, and `@fallback` for analytics, global loading indicators, or coordinating UI outside the Suspense boundary.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const isLoading = ref(false)
|
||||
|
||||
const onPending = () => {
|
||||
isLoading.value = true
|
||||
}
|
||||
|
||||
const onResolve = () => {
|
||||
isLoading.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<LoadingBar v-if="isLoading" />
|
||||
|
||||
<Suspense @pending="onPending" @resolve="onResolve">
|
||||
<AsyncPage />
|
||||
<template #fallback>
|
||||
<PageSkeleton />
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Recommended Nesting with RouterView, Transition, KeepAlive
|
||||
|
||||
When combining these components, the nesting order should be `RouterView` -> `Transition` -> `KeepAlive` -> `Suspense` so each wrapper works correctly.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<RouterView v-slot="{ Component }">
|
||||
<Suspense>
|
||||
<KeepAlive>
|
||||
<Transition mode="out-in">
|
||||
<component :is="Component" />
|
||||
</Transition>
|
||||
</KeepAlive>
|
||||
</Suspense>
|
||||
</RouterView>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<RouterView v-slot="{ Component }">
|
||||
<Transition mode="out-in">
|
||||
<KeepAlive>
|
||||
<Suspense>
|
||||
<component :is="Component" />
|
||||
<template #fallback>Loading...</template>
|
||||
</Suspense>
|
||||
</KeepAlive>
|
||||
</Transition>
|
||||
</RouterView>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Treat Suspense Cautiously in Production
|
||||
|
||||
In production code, keep Suspense boundaries minimal, document where they are used, and have a fallback loading strategy if you ever need to replace or refactor them.
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
title: Teleport Component Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Teleport renders content outside the component's DOM position, which is essential for overlays but affects styling and layout
|
||||
type: best-practice
|
||||
tags: [vue3, teleport, modal, overlay, positioning, responsive]
|
||||
---
|
||||
|
||||
# Teleport Component Best Practices
|
||||
|
||||
**Impact: MEDIUM** - `<Teleport>` renders part of a component's template in a different place in the DOM while preserving the Vue component hierarchy. Use it for overlays (modals, toasts, tooltips) or any UI that must escape stacking contexts, overflow, or fixed positioning constraints.
|
||||
|
||||
## Task List
|
||||
|
||||
- Teleport overlays to `body` or a dedicated container outside the app root
|
||||
- Keep a shared target for similar UI (`#modals`, `#notifications`) and control layering with order or z-index
|
||||
- Use `:disabled` for responsive layouts that should render inline on small screens
|
||||
- Remember props, emits, and provide/inject still work through teleport
|
||||
- Avoid relying on parent stacking contexts or transforms for teleported UI
|
||||
|
||||
## Teleport Overlays Out of Transformed Containers
|
||||
|
||||
When an ancestor has `transform`, `filter`, or `perspective`, fixed-position overlays can behave like they are locally positioned. Teleport escapes that context.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<div class="animated-container">
|
||||
<button @click="open = true">Open</button>
|
||||
|
||||
<!-- Broken: fixed positioning is scoped to the transformed parent -->
|
||||
<div v-if="open" class="modal">Modal</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.animated-container {
|
||||
transform: translateZ(0);
|
||||
}
|
||||
|
||||
.modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9999;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<div class="animated-container">
|
||||
<button @click="open = true">Open</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="modal">Modal</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Responsive Layouts with `disabled`
|
||||
|
||||
Use `:disabled` to render inline on mobile and teleport on larger screens:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useMediaQuery } from '@vueuse/core'
|
||||
|
||||
const isMobile = useMediaQuery('(max-width: 768px)')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body" :disabled="isMobile">
|
||||
<nav class="sidebar">Navigation</nav>
|
||||
</Teleport>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Logical Hierarchy Is Preserved
|
||||
|
||||
Teleport changes DOM position, not the Vue component tree. Props, emits, slots, and provide/inject still work:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<ChildPanel :message="message" @close="open = false" />
|
||||
</Teleport>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Multiple Teleports to the Same Target
|
||||
|
||||
Teleports to the same target append in declaration order:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<Teleport to="#notifications">
|
||||
<div>First</div>
|
||||
</Teleport>
|
||||
|
||||
<Teleport to="#notifications">
|
||||
<div>Second</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
```
|
||||
|
||||
Use a shared container to keep stacking predictable, and apply z-index only when you need explicit layering.
|
||||
@@ -0,0 +1,128 @@
|
||||
---
|
||||
title: TransitionGroup Component Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: TransitionGroup animates list items; missing keys or misuse leads to broken list transitions
|
||||
type: best-practice
|
||||
tags: [vue3, transition-group, animation, lists, keys]
|
||||
---
|
||||
|
||||
# TransitionGroup Component Best Practices
|
||||
|
||||
**Impact: MEDIUM** - `<TransitionGroup>` animates lists of items entering, leaving, and moving. Use it for `v-for` lists or dynamic collections where individual items change over time.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use `<TransitionGroup>` only for lists and repeated items
|
||||
- Provide unique, stable keys for every direct child
|
||||
- Use `tag` when you need semantic or layout wrappers
|
||||
- Avoid the `mode` prop (not supported)
|
||||
- Use JavaScript hooks for staggered effects
|
||||
|
||||
## Use TransitionGroup for Lists
|
||||
|
||||
`<TransitionGroup>` is designed for list items. Use `tag` to control the wrapper element when needed.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup name="fade">
|
||||
<ComponentA />
|
||||
<ComponentB />
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup name="list" tag="ul">
|
||||
<li v-for="item in items" :key="item.id">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Always Provide Stable Keys
|
||||
|
||||
Keys are required. Without stable keys, Vue cannot track item positions and animations break.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup name="list" tag="ul">
|
||||
<li v-for="(item, index) in items" :key="index">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup name="list" tag="ul">
|
||||
<li v-for="item in items" :key="item.id">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Do Not Use `mode` on TransitionGroup
|
||||
|
||||
`mode` is only for `<Transition>` because it swaps a single element. Use `<Transition>` if you need in/out sequencing.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup name="list" tag="div" mode="out-in">
|
||||
<div v-for="item in items" :key="item.id">{{ item.name }}</div>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade" mode="out-in">
|
||||
<component :is="currentView" :key="currentView" />
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Stagger List Animations with Data Attributes
|
||||
|
||||
For cascading list animations, pass the index to JavaScript hooks and compute delay per item.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup
|
||||
tag="ul"
|
||||
:css="false"
|
||||
@before-enter="onBeforeEnter"
|
||||
@enter="onEnter"
|
||||
>
|
||||
<li v-for="(item, index) in items" :key="item.id" :data-index="index">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
function onBeforeEnter(el) {
|
||||
el.style.opacity = 0
|
||||
el.style.transform = 'translateY(12px)'
|
||||
}
|
||||
|
||||
function onEnter(el, done) {
|
||||
const delay = Number(el.dataset.index) * 80
|
||||
setTimeout(() => {
|
||||
el.style.transition = 'all 0.25s ease'
|
||||
el.style.opacity = 1
|
||||
el.style.transform = 'translateY(0)'
|
||||
setTimeout(done, 250)
|
||||
}, delay)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
title: Transition Component Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Transition animates a single element or component; incorrect structure or keys prevent animations
|
||||
type: best-practice
|
||||
tags: [vue3, transition, animation, performance, keys]
|
||||
---
|
||||
|
||||
# Transition Component Best Practices
|
||||
|
||||
**Impact: MEDIUM** - `<Transition>` animates entering/leaving of a single element or component. It is ideal for toggling UI states, swapping views, or animating one component at a time.
|
||||
|
||||
## Task List
|
||||
|
||||
- Wrap a single element or component inside `<Transition>`
|
||||
- Provide a `key` when switching between same element types
|
||||
- Use `mode="out-in"` when you need sequential swaps
|
||||
- Prefer `transform` and `opacity` for smooth animations
|
||||
|
||||
## Use Transition for a Single Root Element
|
||||
|
||||
`<Transition>` only supports one direct child. Wrap multiple nodes in a single element or component.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade">
|
||||
<h3>Title</h3>
|
||||
<p>Description</p>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade">
|
||||
<div>
|
||||
<h3>Title</h3>
|
||||
<p>Description</p>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Force Transitions Between Same Element Types
|
||||
|
||||
Vue reuses the same DOM element when the tag type does not change. Add `key` so Vue treats it as a new element and triggers enter/leave.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade">
|
||||
<p v-if="isActive">Active</p>
|
||||
<p v-else>Inactive</p>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade" mode="out-in">
|
||||
<p v-if="isActive" key="active">Active</p>
|
||||
<p v-else key="inactive">Inactive</p>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Use `mode` to Avoid Overlap During Swaps
|
||||
|
||||
When swapping components or views, use `mode="out-in"` to prevent both from being visible at the same time.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade">
|
||||
<component :is="currentView" />
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade" mode="out-in">
|
||||
<component :is="currentView" :key="currentView" />
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Animate `transform` and `opacity` for Performance
|
||||
|
||||
Avoid layout-triggering properties such as `height`, `margin`, or `top`. Use `transform` and `opacity` for smooth, GPU-friendly transitions.
|
||||
|
||||
**BAD:**
|
||||
```css
|
||||
.slide-enter-active,
|
||||
.slide-leave-active {
|
||||
transition: height 0.3s ease;
|
||||
}
|
||||
|
||||
.slide-enter-from,
|
||||
.slide-leave-to {
|
||||
height: 0;
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```css
|
||||
.slide-enter-active,
|
||||
.slide-leave-active {
|
||||
transition: transform 0.3s ease, opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.slide-enter-from {
|
||||
transform: translateX(-12px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.slide-leave-to {
|
||||
transform: translateX(12px);
|
||||
opacity: 0;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,290 @@
|
||||
---
|
||||
title: Composable Organization Patterns
|
||||
impact: MEDIUM
|
||||
impactDescription: Well-structured composables improve maintainability, reusability, and update performance
|
||||
type: best-practice
|
||||
tags: [vue3, composables, composition-api, code-organization, api-design, readonly, utilities]
|
||||
---
|
||||
|
||||
# Composable Organization Patterns
|
||||
|
||||
**Impact: MEDIUM** - Treat composables as reusable, stateful building blocks and keep their code organized by feature concern. This keeps large components maintainable and prevents hard-to-debug mutation and API design issues.
|
||||
|
||||
## Task List
|
||||
|
||||
- Compose complex behavior from small, focused composables
|
||||
- Use options objects for composables with multiple optional parameters
|
||||
- Return readonly state when updates must flow through explicit actions
|
||||
- Keep pure utility functions as plain utilities, not composables
|
||||
- Organize composable and component code by feature concern, and extract composables when components grow
|
||||
|
||||
## Compose Composables from Smaller Primitives
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
const inside = ref(false)
|
||||
const el = ref(null)
|
||||
|
||||
function onMove(e) {
|
||||
x.value = e.pageX
|
||||
y.value = e.pageY
|
||||
if (!el.value) return
|
||||
const r = el.value.getBoundingClientRect()
|
||||
inside.value = x.value >= r.left && x.value <= r.right &&
|
||||
y.value >= r.top && y.value <= r.bottom
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('mousemove', onMove))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', onMove))
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
// composables/useEventListener.js
|
||||
import { onMounted, onUnmounted, toValue } from 'vue'
|
||||
|
||||
export function useEventListener(target, event, callback) {
|
||||
onMounted(() => toValue(target).addEventListener(event, callback))
|
||||
onUnmounted(() => toValue(target).removeEventListener(event, callback))
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// composables/useMouse.js
|
||||
import { ref } from 'vue'
|
||||
import { useEventListener } from './useEventListener'
|
||||
|
||||
export function useMouse() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
useEventListener(window, 'mousemove', (e) => {
|
||||
x.value = e.pageX
|
||||
y.value = e.pageY
|
||||
})
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// composables/useMouseInElement.js
|
||||
import { computed } from 'vue'
|
||||
import { useMouse } from './useMouse'
|
||||
|
||||
export function useMouseInElement(elementRef) {
|
||||
const { x, y } = useMouse()
|
||||
|
||||
const isOutside = computed(() => {
|
||||
if (!elementRef.value) return true
|
||||
const rect = elementRef.value.getBoundingClientRect()
|
||||
return x.value < rect.left || x.value > rect.right ||
|
||||
y.value < rect.top || y.value > rect.bottom
|
||||
})
|
||||
|
||||
return { x, y, isOutside }
|
||||
}
|
||||
```
|
||||
|
||||
## Use Options Object Pattern for Composable Parameters
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
export function useFetch(url, method, headers, timeout, retries, immediate) {
|
||||
// hard to read and easy to misorder
|
||||
}
|
||||
|
||||
useFetch('/api/users', 'GET', null, 5000, 3, true)
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
export function useFetch(url, options = {}) {
|
||||
const {
|
||||
method = 'GET',
|
||||
headers = {},
|
||||
timeout = 30000,
|
||||
retries = 0,
|
||||
immediate = true
|
||||
} = options
|
||||
|
||||
// implementation
|
||||
return { method, headers, timeout, retries, immediate }
|
||||
}
|
||||
|
||||
useFetch('/api/users', {
|
||||
method: 'POST',
|
||||
timeout: 5000,
|
||||
retries: 3
|
||||
})
|
||||
```
|
||||
|
||||
```typescript
|
||||
interface UseCounterOptions {
|
||||
initial?: number
|
||||
min?: number
|
||||
max?: number
|
||||
step?: number
|
||||
}
|
||||
|
||||
export function useCounter(options: UseCounterOptions = {}) {
|
||||
const { initial = 0, min = -Infinity, max = Infinity, step = 1 } = options
|
||||
// implementation
|
||||
}
|
||||
```
|
||||
|
||||
## Return Readonly State with Explicit Actions
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
export function useCart() {
|
||||
const items = ref([])
|
||||
const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0))
|
||||
return { items, total } // any consumer can mutate directly
|
||||
}
|
||||
|
||||
const { items } = useCart()
|
||||
items.value.push({ id: 1, price: 10 })
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import { ref, computed, readonly } from 'vue'
|
||||
|
||||
export function useCart() {
|
||||
const _items = ref([])
|
||||
|
||||
const total = computed(() =>
|
||||
_items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
|
||||
)
|
||||
|
||||
function addItem(product, quantity = 1) {
|
||||
const existing = _items.value.find(item => item.id === product.id)
|
||||
if (existing) {
|
||||
existing.quantity += quantity
|
||||
return
|
||||
}
|
||||
_items.value.push({ ...product, quantity })
|
||||
}
|
||||
|
||||
function removeItem(productId) {
|
||||
_items.value = _items.value.filter(item => item.id !== productId)
|
||||
}
|
||||
|
||||
return {
|
||||
items: readonly(_items),
|
||||
total,
|
||||
addItem,
|
||||
removeItem
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Keep Utilities as Utilities
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
export function useFormatters() {
|
||||
const formatDate = (date) => new Intl.DateTimeFormat('en-US').format(date)
|
||||
const formatCurrency = (amount) =>
|
||||
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount)
|
||||
return { formatDate, formatCurrency }
|
||||
}
|
||||
|
||||
const { formatDate } = useFormatters()
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
// utils/formatters.js
|
||||
export function formatDate(date) {
|
||||
return new Intl.DateTimeFormat('en-US').format(date)
|
||||
}
|
||||
|
||||
export function formatCurrency(amount) {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD'
|
||||
}).format(amount)
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// composables/useInvoiceSummary.js
|
||||
import { computed } from 'vue'
|
||||
import { formatCurrency } from '@/utils/formatters'
|
||||
|
||||
export function useInvoiceSummary(invoiceRef) {
|
||||
const totalLabel = computed(() => formatCurrency(invoiceRef.value.total))
|
||||
return { totalLabel }
|
||||
}
|
||||
```
|
||||
|
||||
## Organize Composable and Component Code by Feature Concern
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed, watch, onMounted } from 'vue'
|
||||
|
||||
const searchQuery = ref('')
|
||||
const items = ref([])
|
||||
const selected = ref(null)
|
||||
const showModal = ref(false)
|
||||
const sortBy = ref('name')
|
||||
const filter = ref('all')
|
||||
const loading = ref(false)
|
||||
|
||||
const filtered = computed(() => items.value.filter(i => i.category === filter.value))
|
||||
function openModal() { showModal.value = true }
|
||||
const sorted = computed(() => [...filtered.value].sort(/* ... */))
|
||||
watch(searchQuery, () => { /* ... */ })
|
||||
onMounted(() => { /* ... */ })
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { useItems } from '@/composables/useItems'
|
||||
import { useSearch } from '@/composables/useSearch'
|
||||
import { useSelectionModal } from '@/composables/useSelectionModal'
|
||||
|
||||
// Data
|
||||
const { items, loading, fetchItems } = useItems()
|
||||
|
||||
// Search/filter/sort
|
||||
const { query, visibleItems } = useSearch(items)
|
||||
|
||||
// Selection + modal
|
||||
const { selectedItem, isModalOpen, selectItem, closeModal } = useSelectionModal()
|
||||
</script>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// composables/useItems.js
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
export function useItems() {
|
||||
const items = ref([])
|
||||
const loading = ref(false)
|
||||
|
||||
async function fetchItems() {
|
||||
loading.value = true
|
||||
try {
|
||||
items.value = await api.getItems()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchItems)
|
||||
return { items, loading, fetchItems }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
title: Directive Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Custom directives are powerful but easy to misuse; following patterns prevents leaks, invalid usage, and unclear abstractions
|
||||
type: best-practice
|
||||
tags: [vue3, directives, custom-directives, composition, typescript]
|
||||
---
|
||||
|
||||
# Directive Best Practices
|
||||
|
||||
**Impact: MEDIUM** - Directives are for low-level DOM access. Use them sparingly, keep them side-effect safe, and prefer components or composables when you need stateful or reusable UI behavior.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use directives only when you need direct DOM access
|
||||
- Do not mutate directive arguments or binding objects
|
||||
- Clean up timers, listeners, and observers in `unmounted`
|
||||
- Register directives in `<script setup>` with the `v-` prefix
|
||||
- In TypeScript projects, type directive values and augment template directive types
|
||||
- Prefer components or composables for complex behavior
|
||||
|
||||
## Treat Directive Arguments as Read-Only
|
||||
|
||||
Directive bindings are not reactive storage. Don’t write to them.
|
||||
|
||||
```ts
|
||||
const vFocus = {
|
||||
mounted(el, binding) {
|
||||
// binding.value is read-only
|
||||
el.focus()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Avoid Directives on Components
|
||||
|
||||
Directives apply to DOM elements. When used on components, they attach to the root element and can break if the root changes.
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<MyInput v-focus />
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- MyInput.vue -->
|
||||
<script setup>
|
||||
const vFocus = (el) => el.focus()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-focus />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Clean Up Side Effects in `unmounted`
|
||||
|
||||
Any timers, listeners, or observers must be removed to avoid leaks.
|
||||
|
||||
```ts
|
||||
const vResize = {
|
||||
mounted(el) {
|
||||
const observer = new ResizeObserver(() => {})
|
||||
observer.observe(el)
|
||||
el._observer = observer
|
||||
},
|
||||
unmounted(el) {
|
||||
el._observer?.disconnect()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Prefer Function Shorthand for Single-Hook Directives
|
||||
|
||||
If you only need `mounted`/`updated`, use the function form.
|
||||
|
||||
```ts
|
||||
const vAutofocus = (el) => el.focus()
|
||||
```
|
||||
|
||||
## Use the `v-` Prefix and Script Setup Registration
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const vFocus = (el) => el.focus()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-focus />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Type Custom Directives in TypeScript Projects
|
||||
|
||||
Use `Directive<Element, ValueType>` so `binding.value` is typed, and augment Vue's template types so directives are recognized in SFC templates.
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
// Untyped directive value and no template type augmentation
|
||||
export const vHighlight = {
|
||||
mounted(el, binding) {
|
||||
el.style.backgroundColor = binding.value
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
import type { Directive } from 'vue'
|
||||
|
||||
type HighlightValue = string
|
||||
|
||||
export const vHighlight = {
|
||||
mounted(el, binding) {
|
||||
el.style.backgroundColor = binding.value
|
||||
}
|
||||
} satisfies Directive<HTMLElement, HighlightValue>
|
||||
|
||||
declare module 'vue' {
|
||||
interface ComponentCustomProperties {
|
||||
vHighlight: typeof vHighlight
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Handle SSR with `getSSRProps`
|
||||
|
||||
Directive hooks such as `mounted` and `updated` do not run during SSR. If a directive sets attributes/classes that affect rendered HTML, provide an SSR equivalent via `getSSRProps` to avoid hydration mismatches.
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
const vTooltip = {
|
||||
mounted(el, binding) {
|
||||
el.setAttribute('data-tooltip', binding.value)
|
||||
el.classList.add('has-tooltip')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
const vTooltip = {
|
||||
mounted(el, binding) {
|
||||
el.setAttribute('data-tooltip', binding.value)
|
||||
el.classList.add('has-tooltip')
|
||||
},
|
||||
getSSRProps(binding) {
|
||||
return {
|
||||
'data-tooltip': binding.value,
|
||||
class: 'has-tooltip'
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Prefer Declarative Templates When Possible
|
||||
|
||||
If a standard attribute or binding works, use it instead of a directive.
|
||||
|
||||
## Decide Between Directives and Components
|
||||
|
||||
Use a directive for DOM-level behavior. Use a component when behavior affects structure, state, or rendering.
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
title: Avoid Excessive Component Abstraction in Large Lists
|
||||
impact: MEDIUM
|
||||
impactDescription: Each component instance has memory and render overhead - abstractions multiply this in lists
|
||||
type: efficiency
|
||||
tags: [vue3, performance, components, abstraction, lists, optimization]
|
||||
---
|
||||
|
||||
# Avoid Excessive Component Abstraction in Large Lists
|
||||
|
||||
**Impact: MEDIUM** - Component instances are more expensive than plain DOM nodes. While abstractions improve code organization, unnecessary nesting creates overhead. In large lists, this overhead multiplies - 100 items with 3 levels of abstraction means 300+ component instances instead of 100.
|
||||
|
||||
Don't avoid abstraction entirely, but be mindful of component depth in frequently-rendered elements like list items.
|
||||
|
||||
## Task List
|
||||
|
||||
- Review list item components for unnecessary wrapper components
|
||||
- Consider flattening component hierarchies in hot paths
|
||||
- Use native elements when a component adds no value
|
||||
- Profile component counts using Vue DevTools
|
||||
- Focus optimization efforts on the most-rendered components
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<!-- BAD: Deep abstraction in list items -->
|
||||
<template>
|
||||
<div class="user-list">
|
||||
<!-- For 100 users: Creates 400 component instances -->
|
||||
<UserCard v-for="user in users" :key="user.id" :user="user" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- UserCard.vue -->
|
||||
<template>
|
||||
<Card> <!-- Wrapper component #1 -->
|
||||
<CardHeader> <!-- Wrapper component #2 -->
|
||||
<UserAvatar :src="user.avatar" /> <!-- Wrapper component #3 -->
|
||||
</CardHeader>
|
||||
<CardBody> <!-- Wrapper component #4 -->
|
||||
<Text>{{ user.name }}</Text>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<!-- Each UserCard creates: Card + CardHeader + CardBody + UserAvatar + Text
|
||||
100 users = 500+ component instances -->
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- GOOD: Flattened structure in list items -->
|
||||
<template>
|
||||
<div class="user-list">
|
||||
<!-- For 100 users: Creates 100 component instances -->
|
||||
<UserCard v-for="user in users" :key="user.id" :user="user" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- UserCard.vue - Flattened, uses native elements -->
|
||||
<template>
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<img :src="user.avatar" :alt="user.name" class="avatar" />
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<span class="user-name">{{ user.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineProps({
|
||||
user: Object
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Styles that would have been in Card, CardHeader, etc. */
|
||||
.card { /* ... */ }
|
||||
.card-header { /* ... */ }
|
||||
.card-body { /* ... */ }
|
||||
.avatar { /* ... */ }
|
||||
</style>
|
||||
```
|
||||
|
||||
## When Abstraction Is Still Worth It
|
||||
|
||||
```vue
|
||||
<!-- Component abstraction is valuable when: -->
|
||||
|
||||
<!-- 1. Complex behavior is encapsulated -->
|
||||
<UserStatusIndicator :user="user" /> <!-- Has logic, tooltips, etc. -->
|
||||
|
||||
<!-- 2. Reused outside of the hot path -->
|
||||
<Card> <!-- OK to use in one-off places, not in 100-item lists -->
|
||||
|
||||
<!-- 3. The list itself is small -->
|
||||
<template v-if="items.length < 20">
|
||||
<FancyItem v-for="item in items" :key="item.id" />
|
||||
</template>
|
||||
|
||||
<!-- 4. Virtualization is used (only ~20 items rendered at once) -->
|
||||
<RecycleScroller :items="items">
|
||||
<template #default="{ item }">
|
||||
<ComplexItem :item="item" /> <!-- OK - only 20 instances exist -->
|
||||
</template>
|
||||
</RecycleScroller>
|
||||
```
|
||||
|
||||
## Measuring Component Overhead
|
||||
|
||||
```javascript
|
||||
// In development, profile component counts
|
||||
import { onMounted, getCurrentInstance } from 'vue'
|
||||
|
||||
onMounted(() => {
|
||||
const instance = getCurrentInstance()
|
||||
let count = 0
|
||||
|
||||
function countComponents(vnode) {
|
||||
if (vnode.component) count++
|
||||
if (vnode.children) {
|
||||
vnode.children.forEach(child => {
|
||||
if (child.component || child.children) countComponents(child)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Use Vue DevTools instead for accurate counts
|
||||
console.log('Check Vue DevTools Components tab for instance counts')
|
||||
})
|
||||
```
|
||||
|
||||
## Alternatives to Wrapper Components
|
||||
|
||||
```vue
|
||||
<!-- Instead of a <Button> component for styling: -->
|
||||
<button class="btn btn-primary">Click</button>
|
||||
|
||||
<!-- Instead of a <Text> component: -->
|
||||
<span class="text-body">{{ content }}</span>
|
||||
|
||||
<!-- Instead of layout wrapper components in lists: -->
|
||||
<div class="flex items-center gap-2">
|
||||
<!-- content -->
|
||||
</div>
|
||||
|
||||
<!-- Use CSS classes or Tailwind instead of component abstractions for styling -->
|
||||
```
|
||||
|
||||
## Impact Calculation
|
||||
|
||||
| List Size | Components per Item | Total Instances | Memory Impact |
|
||||
|-----------|---------------------|-----------------|---------------|
|
||||
| 100 items | 1 (flat) | 100 | Baseline |
|
||||
| 100 items | 3 (nested) | 300 | ~3x memory |
|
||||
| 100 items | 5 (deeply nested) | 500 | ~5x memory |
|
||||
| 1000 items | 1 (flat) | 1000 | High |
|
||||
| 1000 items | 5 (deeply nested) | 5000 | Very High |
|
||||
@@ -0,0 +1,182 @@
|
||||
---
|
||||
title: Use v-once and v-memo to Skip Unnecessary Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: v-once skips all future updates for static content; v-memo conditionally memoizes subtrees
|
||||
type: efficiency
|
||||
tags: [vue3, performance, v-once, v-memo, optimization, directives]
|
||||
---
|
||||
|
||||
# Use v-once and v-memo to Skip Unnecessary Updates
|
||||
|
||||
**Impact: MEDIUM** - Vue re-evaluates templates on every reactive change. For content that never changes or changes infrequently, `v-once` and `v-memo` tell Vue to skip updates, reducing render work.
|
||||
|
||||
Use `v-once` for truly static content and `v-memo` for conditionally-static content in lists.
|
||||
|
||||
## Task List
|
||||
|
||||
- Apply `v-once` to elements that use runtime data but never need updating
|
||||
- Apply `v-memo` to list items that should only update on specific condition changes
|
||||
- Verify memoized content doesn't need to respond to other state changes
|
||||
- Profile with Vue DevTools to confirm update skipping
|
||||
|
||||
## v-once: Render Once, Never Update
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- BAD: Re-evaluated on every parent re-render -->
|
||||
<div class="terms-content">
|
||||
<h1>Terms of Service</h1>
|
||||
<p>Version: {{ termsVersion }}</p>
|
||||
<div v-html="termsContent"></div>
|
||||
</div>
|
||||
|
||||
<!-- This content NEVER changes, but Vue checks it every render -->
|
||||
<footer>
|
||||
<p>Copyright {{ copyrightYear }} {{ companyName }}</p>
|
||||
</footer>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Rendered once, skipped on all future updates -->
|
||||
<div class="terms-content" v-once>
|
||||
<h1>Terms of Service</h1>
|
||||
<p>Version: {{ termsVersion }}</p>
|
||||
<div v-html="termsContent"></div>
|
||||
</div>
|
||||
|
||||
<!-- v-once tells Vue this never needs to update -->
|
||||
<footer v-once>
|
||||
<p>Copyright {{ copyrightYear }} {{ companyName }}</p>
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// These values are set once at component creation
|
||||
const termsVersion = '2.1'
|
||||
const termsContent = fetchedTermsHTML
|
||||
const copyrightYear = 2024
|
||||
const companyName = 'Acme Corp'
|
||||
</script>
|
||||
```
|
||||
|
||||
## v-memo: Conditional Memoization for Lists
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- BAD: All items re-render when selectedId changes -->
|
||||
<div v-for="item in list" :key="item.id">
|
||||
<div :class="{ selected: item.id === selectedId }">
|
||||
<ExpensiveComponent :data="item" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Items only re-render when their selection state changes -->
|
||||
<div
|
||||
v-for="item in list"
|
||||
:key="item.id"
|
||||
v-memo="[item.id === selectedId]"
|
||||
>
|
||||
<div :class="{ selected: item.id === selectedId }">
|
||||
<ExpensiveComponent :data="item" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const list = ref([/* many items */])
|
||||
const selectedId = ref(null)
|
||||
|
||||
// When selectedId changes:
|
||||
// - Only the previously-selected item re-renders (selected: true -> false)
|
||||
// - Only the newly-selected item re-renders (selected: false -> true)
|
||||
// - All other items are SKIPPED (v-memo values unchanged)
|
||||
</script>
|
||||
```
|
||||
|
||||
## v-memo with Multiple Dependencies
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Re-render only when item's selection OR editing state changes -->
|
||||
<div
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
v-memo="[item.id === selectedId, item.id === editingId]"
|
||||
>
|
||||
<ItemCard
|
||||
:item="item"
|
||||
:selected="item.id === selectedId"
|
||||
:editing="item.id === editingId"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
const selectedId = ref(null)
|
||||
const editingId = ref(null)
|
||||
const items = ref([/* ... */])
|
||||
</script>
|
||||
```
|
||||
|
||||
## v-memo with Empty Array = v-once
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- v-memo="[]" is equivalent to v-once -->
|
||||
<div v-for="item in staticList" :key="item.id" v-memo="[]">
|
||||
{{ item.name }}
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## When NOT to Use These Directives
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- DON'T: Content that DOES need to update -->
|
||||
<div v-once>
|
||||
<span>Count: {{ count }}</span> <!-- count won't update! -->
|
||||
</div>
|
||||
|
||||
<!-- DON'T: When child components have their own reactive state -->
|
||||
<div v-memo="[selected]">
|
||||
<InputField v-model="item.name" /> <!-- v-model won't work properly -->
|
||||
</div>
|
||||
|
||||
<!-- DON'T: When the memoization benefit is minimal -->
|
||||
<span v-once>{{ simpleText }}</span> <!-- Overhead not worth it -->
|
||||
</template>
|
||||
```
|
||||
|
||||
## Performance Comparison
|
||||
|
||||
| Scenario | Without Directive | With v-once/v-memo |
|
||||
|----------|-------------------|-------------------|
|
||||
| Static header, parent re-renders 100x | Re-evaluated 100x | Evaluated 1x |
|
||||
| 1000 items, selection changes | 1000 items re-render | 2 items re-render |
|
||||
| Complex child component | Full re-render | Skipped if memoized |
|
||||
|
||||
## Debugging Memoized Components
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { onUpdated } from 'vue'
|
||||
|
||||
// This won't fire if v-memo prevents update
|
||||
onUpdated(() => {
|
||||
console.log('Component updated')
|
||||
})
|
||||
</script>
|
||||
```
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: Virtualize Large Lists to Avoid DOM Overload
|
||||
impact: HIGH
|
||||
impactDescription: Rendering thousands of list items creates excessive DOM nodes, causing slow renders and high memory usage
|
||||
type: efficiency
|
||||
tags: [vue3, performance, virtual-list, large-data, dom, optimization]
|
||||
---
|
||||
|
||||
# Virtualize Large Lists to Avoid DOM Overload
|
||||
|
||||
**Impact: HIGH** - Rendering all items in a large list (hundreds or thousands) creates massive amounts of DOM nodes. Each node consumes memory, slows down initial render, and makes updates expensive. List virtualization only renders visible items, dramatically improving performance.
|
||||
|
||||
Use a virtualization library when dealing with lists that could exceed 50-100 items, especially if items have complex content.
|
||||
|
||||
## Task List
|
||||
|
||||
- Identify lists that render more than 50-100 items
|
||||
- Install a virtualization library (vue-virtual-scroller, @tanstack/vue-virtual)
|
||||
- Replace standard `v-for` with virtualized component
|
||||
- Ensure list items have consistent or estimable heights
|
||||
- Test with realistic data volumes during development
|
||||
|
||||
## Recommended Libraries
|
||||
|
||||
| Library | Best For | Notes |
|
||||
|---------|----------|-------|
|
||||
| `vue-virtual-scroller` | General use, easy setup | Most popular, good defaults |
|
||||
| `@tanstack/vue-virtual` | Complex layouts, headless | Framework-agnostic, flexible |
|
||||
| `vue-virtual-scroll-grid` | Grid layouts | 2D virtualization |
|
||||
| `vueuc/VVirtualList` | Naive UI projects | Part of Naive UI ecosystem |
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- BAD: Renders ALL 10,000 items immediately -->
|
||||
<div class="user-list">
|
||||
<UserCard
|
||||
v-for="user in users"
|
||||
:key="user.id"
|
||||
:user="user"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import UserCard from './UserCard.vue'
|
||||
|
||||
const users = ref([])
|
||||
|
||||
onMounted(async () => {
|
||||
// 10,000 DOM nodes created, browser struggles
|
||||
users.value = await fetchAllUsers()
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Only renders ~20 visible items at a time -->
|
||||
<RecycleScroller
|
||||
class="user-list"
|
||||
:items="users"
|
||||
:item-size="80"
|
||||
key-field="id"
|
||||
v-slot="{ item }"
|
||||
>
|
||||
<UserCard :user="item" />
|
||||
</RecycleScroller>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { RecycleScroller } from 'vue-virtual-scroller'
|
||||
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
|
||||
import UserCard from './UserCard.vue'
|
||||
|
||||
const users = ref([])
|
||||
|
||||
onMounted(async () => {
|
||||
// 10,000 items in memory, but only ~20 DOM nodes
|
||||
users.value = await fetchAllUsers()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.user-list {
|
||||
height: 600px; /* Container must have fixed height */
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Using @tanstack/vue-virtual
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div ref="parentRef" class="list-container">
|
||||
<div
|
||||
:style="{
|
||||
height: `${rowVirtualizer.getTotalSize()}px`,
|
||||
position: 'relative'
|
||||
}"
|
||||
>
|
||||
<div
|
||||
v-for="virtualRow in rowVirtualizer.getVirtualItems()"
|
||||
:key="virtualRow.key"
|
||||
:style="{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: `${virtualRow.size}px`,
|
||||
transform: `translateY(${virtualRow.start}px)`
|
||||
}"
|
||||
>
|
||||
<UserCard :user="users[virtualRow.index]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { useVirtualizer } from '@tanstack/vue-virtual'
|
||||
|
||||
const users = ref([/* 10,000 users */])
|
||||
const parentRef = ref(null)
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: users.value.length,
|
||||
getScrollElement: () => parentRef.value,
|
||||
estimateSize: () => 80, // Estimated row height
|
||||
overscan: 5 // Render 5 extra items above/below viewport
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.list-container {
|
||||
height: 600px;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Dynamic Heights with vue-virtual-scroller
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- For variable height items, use DynamicScroller -->
|
||||
<DynamicScroller
|
||||
:items="messages"
|
||||
:min-item-size="54"
|
||||
key-field="id"
|
||||
>
|
||||
<template #default="{ item, index, active }">
|
||||
<DynamicScrollerItem
|
||||
:item="item"
|
||||
:active="active"
|
||||
:data-index="index"
|
||||
>
|
||||
<ChatMessage :message="item" />
|
||||
</DynamicScrollerItem>
|
||||
</template>
|
||||
</DynamicScroller>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { DynamicScroller, DynamicScrollerItem } from 'vue-virtual-scroller'
|
||||
</script>
|
||||
```
|
||||
|
||||
## Performance Comparison
|
||||
|
||||
| Approach | 100 Items | 1,000 Items | 10,000 Items |
|
||||
|----------|-----------|-------------|--------------|
|
||||
| Regular v-for | ~100 DOM nodes | ~1,000 DOM nodes | ~10,000 DOM nodes |
|
||||
| Virtualized | ~20 DOM nodes | ~20 DOM nodes | ~20 DOM nodes |
|
||||
| Initial render | Fast | Slow | Very slow / crashes |
|
||||
| Virtualized render | Fast | Fast | Fast |
|
||||
|
||||
## When NOT to Virtualize
|
||||
|
||||
- Lists under 50 items with simple content
|
||||
- Lists where all items must be accessible to screen readers simultaneously
|
||||
- Print layouts where all content must render
|
||||
- SEO-critical content that must be in initial HTML
|
||||
@@ -0,0 +1,166 @@
|
||||
---
|
||||
title: Vue Plugin Best Practices
|
||||
impact: MEDIUM
|
||||
impactDescription: Incorrect plugin structure or injection key strategy causes install failures, collisions, and unsafe APIs
|
||||
type: best-practice
|
||||
tags: [vue3, plugins, provide-inject, typescript, dependency-injection]
|
||||
---
|
||||
|
||||
# Vue Plugin Best Practices
|
||||
|
||||
**Impact: MEDIUM** - Vue plugins should follow the `app.use()` contract, expose explicit capabilities, and use collision-safe injection keys. This keeps plugin setup predictable and composable across large apps.
|
||||
|
||||
## Task List
|
||||
|
||||
- Export plugins as an object with `install()` or as an install function
|
||||
- Use the `app` instance in `install()` to register components/directives/provides
|
||||
- Type plugin APIs with `Plugin` (and options tuple types when needed)
|
||||
- Use symbol keys (prefer `InjectionKey<T>`) for `provide/inject` in plugins
|
||||
- Add a small typed composable wrapper for required injections to fail fast
|
||||
|
||||
## Structure Plugins for `app.use()`
|
||||
|
||||
A Vue plugin must be either:
|
||||
- An object with `install(app, options?)`
|
||||
- A function with the same signature
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
const notAPlugin = {
|
||||
doSomething() {}
|
||||
}
|
||||
|
||||
app.use(notAPlugin)
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
import type { App } from 'vue'
|
||||
|
||||
interface PluginOptions {
|
||||
prefix?: string
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
const myPlugin = {
|
||||
install(app: App, options: PluginOptions = {}) {
|
||||
const { prefix = 'my', debug = false } = options
|
||||
|
||||
if (debug) {
|
||||
console.log('Installing myPlugin with prefix:', prefix)
|
||||
}
|
||||
|
||||
app.provide('myPlugin', { prefix })
|
||||
}
|
||||
}
|
||||
|
||||
app.use(myPlugin, { prefix: 'custom', debug: true })
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
import type { App } from 'vue'
|
||||
|
||||
function simplePlugin(app: App, options?: { message: string }) {
|
||||
app.config.globalProperties.$greet = () => options?.message ?? 'Hello!'
|
||||
}
|
||||
|
||||
app.use(simplePlugin, { message: 'Welcome!' })
|
||||
```
|
||||
|
||||
## Register Capabilities Explicitly in `install()`
|
||||
|
||||
Inside `install()`, wire behavior through Vue application APIs:
|
||||
- `app.component()` for global components
|
||||
- `app.directive()` for global directives
|
||||
- `app.provide()` for injectable services and config
|
||||
- `app.config.globalProperties` for optional global helpers (sparingly)
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
const uselessPlugin = {
|
||||
install(app, options) {
|
||||
const service = createService(options)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
const usefulPlugin = {
|
||||
install(app, options) {
|
||||
const service = createService(options)
|
||||
app.provide(serviceKey, service)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Type Plugin Contracts
|
||||
|
||||
Use Vue's `Plugin` type to keep install signatures and options type-safe.
|
||||
|
||||
```ts
|
||||
import type { App, Plugin } from 'vue'
|
||||
|
||||
interface MyOptions {
|
||||
apiKey: string
|
||||
}
|
||||
|
||||
const myPlugin: Plugin<[MyOptions]> = {
|
||||
install(app: App, options: MyOptions) {
|
||||
app.provide(apiKeyKey, options.apiKey)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use Symbol Injection Keys in Plugins
|
||||
|
||||
String keys can collide (`'http'`, `'config'`, `'i18n'`). Use symbol keys with `InjectionKey<T>` so injections are unique and typed.
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
export default {
|
||||
install(app) {
|
||||
app.provide('http', axios)
|
||||
app.provide('config', appConfig)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
import type { InjectionKey } from 'vue'
|
||||
import type { AxiosInstance } from 'axios'
|
||||
|
||||
interface AppConfig {
|
||||
apiUrl: string
|
||||
timeout: number
|
||||
}
|
||||
|
||||
export const httpKey: InjectionKey<AxiosInstance> = Symbol('http')
|
||||
export const configKey: InjectionKey<AppConfig> = Symbol('appConfig')
|
||||
|
||||
export default {
|
||||
install(app) {
|
||||
app.provide(httpKey, axios)
|
||||
app.provide(configKey, { apiUrl: '/api', timeout: 5000 })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Provide Required Injection Helpers
|
||||
|
||||
Wrap required injections in composables that throw clear setup errors.
|
||||
|
||||
```ts
|
||||
import { inject } from 'vue'
|
||||
import { authKey, type AuthService } from '@/injection-keys'
|
||||
|
||||
export function useAuth(): AuthService {
|
||||
const auth = inject(authKey)
|
||||
if (!auth) {
|
||||
throw new Error('Auth plugin not installed. Did you forget app.use(authPlugin)?')
|
||||
}
|
||||
return auth
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,344 @@
|
||||
---
|
||||
title: Reactivity Core Patterns (ref, reactive, shallowRef, computed, watch)
|
||||
impact: MEDIUM
|
||||
impactDescription: Clear reactivity choices keep state predictable and reduce unnecessary updates in Vue 3 apps
|
||||
type: efficiency
|
||||
tags: [vue3, reactivity, ref, reactive, shallowRef, computed, watch, watchEffect, external-state, best-practice]
|
||||
---
|
||||
|
||||
# Reactivity Core Patterns (ref, reactive, shallowRef, computed, watch)
|
||||
|
||||
**Impact: MEDIUM** - Choose the right reactive primitive first, derive with `computed`, and use watchers only for side effects.
|
||||
|
||||
This reference covers the core reactivity decisions for local state, external data, derived values, and effects.
|
||||
|
||||
## Task List
|
||||
|
||||
- Declare reactive state correctly
|
||||
- Always use `shallowRef()` instead of `ref()` for primitive values
|
||||
- Choose the correct reactive declaration method for objects/arrays/map/set
|
||||
- Follow best practices for `reactive`
|
||||
- Avoid destructuring from `reactive()` directly
|
||||
- Watch correctly for `reactive`
|
||||
- Follow best practices for `computed`
|
||||
- Prefer `computed` over watcher-assigned derived refs
|
||||
- Keep filtered/sorted derivations out of templates
|
||||
- Use `computed` for reusable class/style logic
|
||||
- Keep computed getters pure (no side effects) and put side effects in watchers
|
||||
- Follow best practices for watchers
|
||||
- Use `immediate: true` instead of duplicate initial calls
|
||||
- Clean up async effects for watchers
|
||||
|
||||
## Declare reactive state correctly
|
||||
|
||||
### Always use `shallowRef()` instead of `ref()` for primitive values (string, number, boolean, null, etc.) for better performance.
|
||||
|
||||
**Incorrect:**
|
||||
```ts
|
||||
import { ref } from 'vue'
|
||||
const count = ref(0)
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```ts
|
||||
import { shallowRef } from 'vue'
|
||||
const count = shallowRef(0)
|
||||
```
|
||||
|
||||
### Choose the correct reactive declaration method for objects/arrays/map/set
|
||||
|
||||
Use `ref()` when you often **replace the entire value** (`state.value = newObj`) and still want deep reactivity inside it, usually used for:
|
||||
|
||||
- Frequently reassigned state (replace fetched object/list, reset to defaults, switch presets).
|
||||
- Composable return values where updates happen mostly via `.value` reassignment.
|
||||
|
||||
Use `reactive()` when you mainly **mutate properties** and full replacement is uncommon, usually used for:
|
||||
|
||||
- “Single state object” patterns (stores/forms): `state.count++`, `state.items.push(...)`, `state.user.name = ...`.
|
||||
- Situations where you want to avoid `.value` and update nested fields in place.
|
||||
|
||||
```ts
|
||||
import { reactive } from 'vue'
|
||||
|
||||
const state = reactive({
|
||||
count: 0,
|
||||
user: { name: 'Alice', age: 30 }
|
||||
})
|
||||
|
||||
state.count++ // ✅ reactive
|
||||
state.user.age = 31 // ✅ reactive
|
||||
// ❌ avoid replacing the reactive object reference:
|
||||
// state = reactive({ count: 1 })
|
||||
```
|
||||
|
||||
Use `shallowRef()` when the value is **opaque / should not be proxied** (class instances, external library objects, very large nested data) and you only want updates to trigger when you **replace** `state.value` (no deep tracking), usually used for:
|
||||
|
||||
- Storing external instances/handles (SDK clients, class instances) without Vue proxying internals.
|
||||
- Large data where you update by replacing the root reference (immutable-style updates).
|
||||
|
||||
```ts
|
||||
import { shallowRef } from 'vue'
|
||||
|
||||
const user = shallowRef({ name: 'Alice', age: 30 })
|
||||
|
||||
user.value.age = 31 // ❌ not reactive
|
||||
user.value = { name: 'Bob', age: 25 } // ✅ triggers update
|
||||
```
|
||||
|
||||
Use `shallowReactive()` when you want **only top-level properties** reactive; nested objects remain raw, usually used for:
|
||||
|
||||
- Container objects where only top-level keys change and nested payloads should stay unmanaged/unproxied.
|
||||
- Mixed structures where Vue tracks the wrapper object, but not deeply nested or foreign objects.
|
||||
|
||||
```ts
|
||||
import { shallowReactive } from 'vue'
|
||||
|
||||
const state = shallowReactive({
|
||||
count: 0,
|
||||
user: { name: 'Alice', age: 30 }
|
||||
})
|
||||
|
||||
state.count++ // ✅ reactive
|
||||
state.user.age = 31 // ❌ not reactive
|
||||
```
|
||||
|
||||
## Best practices for `reactive`
|
||||
|
||||
### Avoid destructuring from `reactive()` directly
|
||||
|
||||
**BAD:**
|
||||
|
||||
```ts
|
||||
import { reactive } from 'vue'
|
||||
|
||||
const state = reactive({ count: 0 })
|
||||
const { count } = state // ❌ disconnected from reactivity
|
||||
```
|
||||
|
||||
### Watch correctly for reactive
|
||||
|
||||
**BAD:**
|
||||
|
||||
passing a non-getter value into `watch()`
|
||||
|
||||
```ts
|
||||
import { reactive, watch } from 'vue'
|
||||
|
||||
const state = reactive({ count: 0 })
|
||||
|
||||
// ❌ watch expects a getter, ref, reactive object, or array of these
|
||||
watch(state.count, () => { /* ... */ })
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
preserve reactivity with `toRefs()` and use a getter for `watch()`
|
||||
|
||||
```ts
|
||||
import { reactive, toRefs, watch } from 'vue'
|
||||
|
||||
const state = reactive({ count: 0 })
|
||||
const { count } = toRefs(state) // ✅ count is a ref
|
||||
|
||||
watch(count, () => { /* ... */ }) // ✅
|
||||
watch(() => state.count, () => { /* ... */ }) // ✅
|
||||
```
|
||||
|
||||
## Best practices for `computed`
|
||||
|
||||
### Prefer `computed` over watcher-assigned derived refs
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
import { ref, watchEffect } from 'vue'
|
||||
|
||||
const items = ref([{ price: 10 }, { price: 20 }])
|
||||
const total = ref(0)
|
||||
|
||||
watchEffect(() => {
|
||||
total.value = items.value.reduce((sum, item) => sum + item.price, 0)
|
||||
})
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([{ price: 10 }, { price: 20 }])
|
||||
const total = computed(() =>
|
||||
items.value.reduce((sum, item) => sum + item.price, 0)
|
||||
)
|
||||
```
|
||||
|
||||
### Keep filtered/sorted derivations out of templates
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<li v-for="item in items.filter(item => item.active)" :key="item.id">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
|
||||
<li v-for="item in getSortedItems()" :key="item.id">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const items = ref([
|
||||
{ id: 1, name: 'B', active: true },
|
||||
{ id: 2, name: 'A', active: false }
|
||||
])
|
||||
|
||||
function getSortedItems() {
|
||||
return [...items.value].sort((a, b) => a.name.localeCompare(b.name))
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([
|
||||
{ id: 1, name: 'B', active: true },
|
||||
{ id: 2, name: 'A', active: false }
|
||||
])
|
||||
|
||||
const visibleItems = computed(() =>
|
||||
items.value
|
||||
.filter(item => item.active)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<li v-for="item in visibleItems" :key="item.id">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Use `computed` for reusable class/style logic
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<button :class="{ btn: true, 'btn-primary': type === 'primary' && !disabled, 'btn-disabled': disabled }">
|
||||
{{ label }}
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
type: { type: String, default: 'primary' },
|
||||
disabled: Boolean,
|
||||
label: String
|
||||
})
|
||||
|
||||
const buttonClasses = computed(() => ({
|
||||
btn: true,
|
||||
[`btn-${props.type}`]: !props.disabled,
|
||||
'btn-disabled': props.disabled
|
||||
}))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button :class="buttonClasses">
|
||||
{{ label }}
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Keep computed getters pure (no side effects) and put side effects in watchers instead
|
||||
|
||||
A computed getter should only derive a value. No mutation, no API calls, no storage writes, no event emits.
|
||||
([Reference](https://vuejs.org/guide/essentials/computed.html#best-practices))
|
||||
|
||||
**BAD:**
|
||||
|
||||
side effects inside computed
|
||||
|
||||
```ts
|
||||
const count = ref(0)
|
||||
|
||||
const doubled = computed(() => {
|
||||
// ❌ side effect
|
||||
if (count.value > 10) console.warn('Too big!')
|
||||
return count.value * 2
|
||||
})
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
pure computed + `watch()` for side effects
|
||||
|
||||
```ts
|
||||
const count = ref(0)
|
||||
const doubled = computed(() => count.value * 2)
|
||||
|
||||
watch(count, (value) => {
|
||||
if (value > 10) console.warn('Too big!')
|
||||
})
|
||||
```
|
||||
|
||||
## Best practices for watchers
|
||||
|
||||
### Use `immediate: true` instead of duplicate initial calls
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
import { ref, watch, onMounted } from 'vue'
|
||||
|
||||
const userId = ref(1)
|
||||
|
||||
function loadUser(id) {
|
||||
// ...
|
||||
}
|
||||
|
||||
onMounted(() => loadUser(userId.value))
|
||||
watch(userId, (id) => loadUser(id))
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
const userId = ref(1)
|
||||
|
||||
watch(
|
||||
userId,
|
||||
(id) => loadUser(id),
|
||||
{ immediate: true }
|
||||
)
|
||||
```
|
||||
|
||||
### Clean up async effects for watchers
|
||||
|
||||
When reacting to rapid changes (search boxes, filters), cancel the previous request.
|
||||
|
||||
**GOOD:**
|
||||
|
||||
```ts
|
||||
const query = ref('')
|
||||
const results = ref<string[]>([])
|
||||
|
||||
watch(query, async (q, _prev, onCleanup) => {
|
||||
const controller = new AbortController()
|
||||
onCleanup(() => controller.abort())
|
||||
|
||||
const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
results.value = await res.json()
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,201 @@
|
||||
---
|
||||
title: Render Function Patterns and Performance
|
||||
impact: MEDIUM
|
||||
impactDescription: Render functions require explicit patterns for lists, events, v-model, and performance to stay correct and maintainable
|
||||
type: best-practice
|
||||
tags: [vue3, render-function, h, v-model, directives, performance, jsx]
|
||||
---
|
||||
|
||||
# Render Function Patterns and Performance
|
||||
|
||||
**Impact: MEDIUM** - Render functions are powerful but opt out of template compiler optimizations. Use them intentionally and apply the key patterns below to keep output correct and performant.
|
||||
|
||||
## Task List
|
||||
|
||||
- Prefer templates; use render functions only when templates cannot express the logic
|
||||
- Always add stable keys when rendering lists with `h()`/JSX
|
||||
- Use `withModifiers` / `withKeys` for event modifiers
|
||||
- Implement `v-model` via `modelValue` + `onUpdate:modelValue`
|
||||
- Apply custom directives with `withDirectives`
|
||||
- Use functional components for stateless presentational UI
|
||||
|
||||
## Prefer templates over render functions
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { h, ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
const render = () => h('div', `Count: ${count.value}`)
|
||||
</script>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>Count: {{ count }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Always add keys for list rendering
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
import { h, ref } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const items = ref([{ id: 1, name: 'Apple' }])
|
||||
|
||||
return () => h('ul',
|
||||
items.value.map(item => h('li', item.name))
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import { h, ref } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const items = ref([{ id: 1, name: 'Apple' }])
|
||||
|
||||
return () => h('ul',
|
||||
items.value.map(item => h('li', { key: item.id }, item.name))
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use `withModifiers` / `withKeys` for event modifiers
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
import { h } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const handleClick = (e) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
return () => h('button', { onClick: handleClick }, 'Click')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import { h, withModifiers, withKeys } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const handleClick = () => {}
|
||||
const handleEnter = () => {}
|
||||
|
||||
return () => h('div', [
|
||||
h('button', {
|
||||
onClick: withModifiers(handleClick, ['stop', 'prevent'])
|
||||
}, 'Click'),
|
||||
h('input', {
|
||||
onKeyup: withKeys(handleEnter, ['enter'])
|
||||
})
|
||||
])
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Implement `v-model` explicitly
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
import { h, ref } from 'vue'
|
||||
import CustomInput from './CustomInput.vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const text = ref('')
|
||||
return () => h(CustomInput, { modelValue: text.value })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import { h, ref } from 'vue'
|
||||
import CustomInput from './CustomInput.vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const text = ref('')
|
||||
return () => h(CustomInput, {
|
||||
modelValue: text.value,
|
||||
'onUpdate:modelValue': (value) => { text.value = value }
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use `withDirectives` for custom directives
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
import { h } from 'vue'
|
||||
|
||||
const vFocus = { mounted: (el) => el.focus() }
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
return () => h('input', { 'v-focus': true })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import { h, withDirectives } from 'vue'
|
||||
|
||||
const vFocus = { mounted: (el) => el.focus() }
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
return () => withDirectives(h('input'), [[vFocus]])
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Prefer functional components for stateless UI
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
import { h } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
return () => h('span', { class: 'badge' }, 'New')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import { h } from 'vue'
|
||||
|
||||
function Badge(props, { slots }) {
|
||||
return h('span', { class: 'badge' }, slots.default?.())
|
||||
}
|
||||
|
||||
Badge.props = ['variant']
|
||||
|
||||
export default Badge
|
||||
```
|
||||
310
1-Vue3-Dev/.agents/skills/vue-best-practices/references/sfc.md
Normal file
310
1-Vue3-Dev/.agents/skills/vue-best-practices/references/sfc.md
Normal file
@@ -0,0 +1,310 @@
|
||||
---
|
||||
title: Single-File Component Structure, Styling, and Template Patterns
|
||||
impact: MEDIUM
|
||||
impactDescription: Consistent SFC structure and styling choices improve maintainability, tooling support, and render performance
|
||||
type: best-practice
|
||||
tags: [vue3, sfc, scoped-css, styles, build-tools, performance, template, v-html, v-for, computed, v-if, v-show]
|
||||
---
|
||||
|
||||
# Single-File Component Structure, Styling, and Template Patterns
|
||||
|
||||
**Impact: MEDIUM** - Using SFCs with consistent structure and performant styling keeps components easier to maintain and avoids unnecessary render overhead.
|
||||
|
||||
## Task List
|
||||
|
||||
- Use `.vue` SFCs instead of separate `.js`/`.ts` and `.css` files for components
|
||||
- Colocate template, script, and styles in the same SFC by default
|
||||
- Use PascalCase for component names in templates and filenames
|
||||
- Prefer component-scoped styles
|
||||
- Prefer class selectors (not element selectors) in scoped CSS for performance
|
||||
- Access DOM / component refs with `useTemplateRef()` in Vue 3.5+
|
||||
- Use camelCase keys in `:style` bindings for consistency and IDE support
|
||||
- Use `v-for` and `v-if` correctly
|
||||
- Never use `v-html` with untrusted/user-provided content
|
||||
- Choose `v-if` vs `v-show` based on toggle frequency and initial render cost
|
||||
|
||||
## Colocate template, script, and styles
|
||||
|
||||
**BAD:**
|
||||
```
|
||||
components/
|
||||
├── UserCard.vue
|
||||
├── UserCard.js
|
||||
└── UserCard.css
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<!-- components/UserCard.vue -->
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
user: { type: Object, required: true }
|
||||
})
|
||||
|
||||
const displayName = computed(() =>
|
||||
`${props.user.firstName} ${props.user.lastName}`
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="user-card">
|
||||
<h3 class="name">{{ displayName }}</h3>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.user-card {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.name {
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Use PascalCase for component names
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import userProfile from './user-profile.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<user-profile :user="currentUser" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import UserProfile from './UserProfile.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UserProfile :user="currentUser" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Best practices for `<style>` block in SFCs
|
||||
|
||||
### Prefer component-scoped styles
|
||||
|
||||
- Use `<style scoped>` for styles that belong to a component.
|
||||
- Keep **global CSS** in a dedicated file (e.g. `src/assets/main.css`) for resets, typography, tokens, etc.
|
||||
- Use `:deep()` sparingly (edge cases only).
|
||||
|
||||
**BAD:**
|
||||
|
||||
```vue
|
||||
<style>
|
||||
/* ❌ leaks everywhere */
|
||||
button { border-radius: 999px; }
|
||||
</style>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
```vue
|
||||
<style scoped>
|
||||
.button { border-radius: 999px; }
|
||||
</style>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
```css
|
||||
/* src/assets/main.css */
|
||||
/* ✅ resets, tokens, typography, app-wide rules */
|
||||
:root { --radius: 999px; }
|
||||
```
|
||||
|
||||
### Use class selectors in scoped CSS
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<article>
|
||||
<h1>{{ title }}</h1>
|
||||
<p>{{ subtitle }}</p>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
article { max-width: 800px; }
|
||||
h1 { font-size: 2rem; }
|
||||
p { line-height: 1.6; }
|
||||
</style>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<article class="article">
|
||||
<h1 class="article-title">{{ title }}</h1>
|
||||
<p class="article-subtitle">{{ subtitle }}</p>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.article { max-width: 800px; }
|
||||
.article-title { font-size: 2rem; }
|
||||
.article-subtitle { line-height: 1.6; }
|
||||
</style>
|
||||
```
|
||||
|
||||
## Access DOM / component refs with `useTemplateRef()`
|
||||
|
||||
For Vue 3.5+: use `useTemplateRef()` to access template refs.
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { onMounted, useTemplateRef } from 'vue'
|
||||
|
||||
const inputRef = useTemplateRef<HTMLInputElement>('input')
|
||||
|
||||
onMounted(() => {
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="input" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Use camelCase in `:style` bindings
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<div :style="{ 'font-size': fontSize + 'px', 'background-color': bg }">
|
||||
Content
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<div :style="{ fontSize: fontSize + 'px', backgroundColor: bg }">
|
||||
Content
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Use `v-for` and `v-if` correctly
|
||||
|
||||
### Always provide a stable `:key`
|
||||
|
||||
- Prefer primitive keys (`string | number`).
|
||||
- Avoid using objects as keys.
|
||||
|
||||
**GOOD:**
|
||||
|
||||
```vue
|
||||
<li v-for="item in items" :key="item.id">
|
||||
<input v-model="item.text" />
|
||||
</li>
|
||||
```
|
||||
|
||||
### Avoid `v-if` and `v-for` on the same element
|
||||
|
||||
It leads to unclear intent and unnecessary work.
|
||||
([Reference](https://vuejs.org/guide/essentials/list.html#v-for-with-v-if))
|
||||
|
||||
**To filter items**
|
||||
**BAD:**
|
||||
|
||||
```vue
|
||||
<li v-for="user in users" v-if="user.active" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const activeUsers = computed(() => users.value.filter(u => u.active))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<li v-for="user in activeUsers" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</template>
|
||||
```
|
||||
|
||||
**To conditionally show/hide the entire list**
|
||||
**GOOD:**
|
||||
|
||||
```vue
|
||||
<ul v-if="shouldShowUsers">
|
||||
<li v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
## Never render untrusted HTML with `v-html`
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- DANGEROUS: untrusted input can inject scripts -->
|
||||
<article v-html="userProvidedContent"></article>
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import DOMPurify from 'dompurify'
|
||||
|
||||
const props = defineProps<{
|
||||
trustedHtml?: string
|
||||
plainText: string
|
||||
}>()
|
||||
|
||||
const safeHtml = computed(() => DOMPurify.sanitize(props.trustedHtml ?? ''))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Preferred: escaped interpolation -->
|
||||
<p>{{ props.plainText }}</p>
|
||||
|
||||
<!-- Only for trusted/sanitized HTML -->
|
||||
<article v-html="safeHtml"></article>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Choose `v-if` vs `v-show` by toggle behavior
|
||||
|
||||
**BAD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- Frequent toggles with v-if cause repeated mount/unmount -->
|
||||
<ComplexPanel v-if="isPanelOpen" />
|
||||
|
||||
<!-- Rarely shown content with v-show pays initial render cost -->
|
||||
<AdminPanel v-show="isAdmin" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- Frequent toggles: keep in DOM, toggle display -->
|
||||
<ComplexPanel v-show="isPanelOpen" />
|
||||
|
||||
<!-- Rare condition: lazy render only when true -->
|
||||
<AdminPanel v-if="isAdmin" />
|
||||
</template>
|
||||
```
|
||||
@@ -0,0 +1,135 @@
|
||||
---
|
||||
title: State Management Strategy
|
||||
impact: HIGH
|
||||
impactDescription: Choosing the wrong store pattern can cause SSR request leaks, brittle mutation flows, and poor scaling
|
||||
type: best-practice
|
||||
tags: [vue3, state-management, pinia, composables, ssr, vueuse]
|
||||
---
|
||||
|
||||
# State Management Strategy
|
||||
|
||||
**Impact: HIGH** - Use the lightest state solution that fits your app architecture. SPA-only apps can use lightweight global composables, while SSR/Nuxt apps should default to Pinia for request-safe isolation and predictable tooling.
|
||||
|
||||
## Task List
|
||||
|
||||
- Keep state local first, then promote to shared/global only when needed
|
||||
- Use singleton composables only in non-SSR applications
|
||||
- Expose global state as readonly and mutate through explicit actions
|
||||
- Prefer Pinia for SSR/Nuxt, large apps, and advanced debugging/plugin needs
|
||||
- Avoid exporting mutable module-level reactive state directly
|
||||
|
||||
## Choose the Lightest Store Approach
|
||||
|
||||
- **Feature composable:** Default for reusable logic with local/feature-level state.
|
||||
- **Singleton composable or VueUse `createGlobalState`:** Small non-SSR apps needing shared app state.
|
||||
- **Pinia:** SSR/Nuxt apps, medium-to-large apps, and cases requiring DevTools, plugins, or action tracing.
|
||||
|
||||
## Avoid Exporting Mutable Module State
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
// store/cart.ts
|
||||
import { reactive } from 'vue'
|
||||
|
||||
export const cart = reactive({
|
||||
items: [] as Array<{ id: string; qty: number }>
|
||||
})
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```ts
|
||||
// composables/useCartStore.ts
|
||||
import { reactive, readonly } from 'vue'
|
||||
|
||||
let _store: ReturnType<typeof createCartStore> | null = null
|
||||
|
||||
function createCartStore() {
|
||||
const state = reactive({
|
||||
items: [] as Array<{ id: string; qty: number }>
|
||||
})
|
||||
|
||||
function addItem(id: string, qty = 1) {
|
||||
const existing = state.items.find((item) => item.id === id)
|
||||
if (existing) {
|
||||
existing.qty += qty
|
||||
return
|
||||
}
|
||||
state.items.push({ id, qty })
|
||||
}
|
||||
|
||||
return {
|
||||
state: readonly(state),
|
||||
addItem
|
||||
}
|
||||
}
|
||||
|
||||
export function useCartStore() {
|
||||
if (!_store) _store = createCartStore()
|
||||
return _store
|
||||
}
|
||||
```
|
||||
|
||||
## Do Not Use Runtime Singletons in SSR
|
||||
|
||||
Module singletons live for the runtime lifetime. In SSR this can leak state between requests.
|
||||
|
||||
**BAD:**
|
||||
```ts
|
||||
// shared singleton reused across requests
|
||||
const cartStore = useCartStore()
|
||||
|
||||
export function useServerCart() {
|
||||
return cartStore
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
|
||||
> `pinia` dependency required.
|
||||
|
||||
```ts
|
||||
// stores/cart.ts
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useCartStore = defineStore('cart', {
|
||||
state: () => ({
|
||||
items: [] as Array<{ id: string; qty: number }>
|
||||
}),
|
||||
actions: {
|
||||
addItem(id: string, qty = 1) {
|
||||
const existing = this.items.find((item) => item.id === id)
|
||||
if (existing) {
|
||||
existing.qty += qty
|
||||
return
|
||||
}
|
||||
this.items.push({ id, qty })
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Use `createGlobalState` for Small SPA Global State
|
||||
|
||||
> `@vueuse/core` dependency required.
|
||||
|
||||
If the app is non-SSR and already uses VueUse, `createGlobalState` removes singleton boilerplate.
|
||||
|
||||
```ts
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
export const useAuthState = createGlobalState(() => {
|
||||
const token = ref<string | null>(null)
|
||||
const isAuthenticated = computed(() => token.value !== null)
|
||||
|
||||
function setToken(next: string | null) {
|
||||
token.value = next
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
isAuthenticated,
|
||||
setToken
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: Avoid Expensive Operations in Updated Hook
|
||||
impact: MEDIUM
|
||||
impactDescription: Heavy computations in updated hook cause performance bottlenecks and potential infinite loops
|
||||
type: capability
|
||||
tags: [vue3, vue2, lifecycle, updated, performance, optimization, reactivity]
|
||||
---
|
||||
|
||||
# Avoid Expensive Operations in Updated Hook
|
||||
|
||||
**Impact: MEDIUM** - The `updated` hook runs after every reactive state change that causes a re-render. Placing expensive operations, API calls, or state mutations here can cause severe performance degradation, infinite loops, and dropped frames below the optimal 60fps threshold.
|
||||
|
||||
Use `updated`/`onUpdated` sparingly for post-DOM-update operations that cannot be handled by watchers or computed properties. For most reactive data handling, prefer watchers (`watch`/`watchEffect`) which provide more control over what triggers the callback.
|
||||
|
||||
## Task List
|
||||
|
||||
- Never perform API calls in updated hook
|
||||
- Never mutate reactive state inside updated (causes infinite loops)
|
||||
- Use conditional checks to verify updates are relevant before acting
|
||||
- Prefer `watch` or `watchEffect` for reacting to specific data changes
|
||||
- Use throttling/debouncing if updated operations are expensive
|
||||
- Reserve updated for low-level DOM synchronization tasks
|
||||
|
||||
**BAD:**
|
||||
```javascript
|
||||
// BAD: API call in updated - fires on every re-render
|
||||
export default {
|
||||
data() {
|
||||
return { items: [], lastUpdate: null }
|
||||
},
|
||||
updated() {
|
||||
// This runs after every single state change!
|
||||
fetch('/api/sync', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(this.items)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// BAD: State mutation in updated - infinite loop
|
||||
export default {
|
||||
data() {
|
||||
return { renderCount: 0 }
|
||||
},
|
||||
updated() {
|
||||
// This causes another update, which triggers updated again!
|
||||
this.renderCount++ // Infinite loop
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// BAD: Heavy computation on every update
|
||||
export default {
|
||||
updated() {
|
||||
// Expensive operation runs on every keystroke, every state change
|
||||
this.processedData = this.heavyComputation(this.rawData)
|
||||
this.analytics = this.calculateMetrics(this.allData)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**GOOD:**
|
||||
```javascript
|
||||
import debounce from 'lodash-es/debounce'
|
||||
|
||||
// GOOD: Use watcher for specific data changes
|
||||
export default {
|
||||
data() {
|
||||
return { items: [] }
|
||||
},
|
||||
watch: {
|
||||
// Only fires when items actually changes
|
||||
items: {
|
||||
handler(newItems) {
|
||||
this.syncToServer(newItems)
|
||||
},
|
||||
deep: true
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
syncToServer: debounce(function(items) {
|
||||
fetch('/api/sync', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(items)
|
||||
})
|
||||
}, 500)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- GOOD: Composition API with targeted watchers -->
|
||||
<script setup>
|
||||
import { ref, watch, onUpdated } from 'vue'
|
||||
import { useDebounceFn } from '@vueuse/core'
|
||||
|
||||
const items = ref([])
|
||||
const scrollContainer = ref(null)
|
||||
|
||||
// Watch specific data - not all updates
|
||||
watch(items, (newItems) => {
|
||||
syncToServer(newItems)
|
||||
}, { deep: true })
|
||||
|
||||
const syncToServer = useDebounceFn((items) => {
|
||||
fetch('/api/sync', { method: 'POST', body: JSON.stringify(items) })
|
||||
}, 500)
|
||||
|
||||
// Only use onUpdated for DOM synchronization
|
||||
onUpdated(() => {
|
||||
// Scroll to bottom only if content changed height
|
||||
if (scrollContainer.value) {
|
||||
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// GOOD: Conditional check in updated hook
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
content: '',
|
||||
lastSyncedContent: ''
|
||||
}
|
||||
},
|
||||
updated() {
|
||||
// Only act if specific condition is met
|
||||
if (this.content !== this.lastSyncedContent) {
|
||||
this.syncContent()
|
||||
this.lastSyncedContent = this.content
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
syncContent: debounce(function() {
|
||||
// Sync logic
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Valid Use Cases for Updated Hook
|
||||
|
||||
```javascript
|
||||
// GOOD: Low-level DOM synchronization
|
||||
export default {
|
||||
updated() {
|
||||
// Sync third-party library with Vue's DOM
|
||||
this.thirdPartyWidget.refresh()
|
||||
|
||||
// Update scroll position after content change
|
||||
this.$nextTick(() => {
|
||||
this.maintainScrollPosition()
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Prefer Computed Properties for Derived Data
|
||||
|
||||
```javascript
|
||||
// BAD: Calculating derived data in updated
|
||||
export default {
|
||||
data() {
|
||||
return { numbers: [1, 2, 3, 4, 5] }
|
||||
},
|
||||
updated() {
|
||||
this.sum = this.numbers.reduce((a, b) => a + b, 0) // Causes another update!
|
||||
}
|
||||
}
|
||||
|
||||
// GOOD: Use computed property instead
|
||||
export default {
|
||||
data() {
|
||||
return { numbers: [1, 2, 3, 4, 5] }
|
||||
},
|
||||
computed: {
|
||||
sum() {
|
||||
return this.numbers.reduce((a, b) => a + b, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
202
1-Vue3-Dev/.agents/skills/vue-debug-guides/SKILL.md
Normal file
202
1-Vue3-Dev/.agents/skills/vue-debug-guides/SKILL.md
Normal file
@@ -0,0 +1,202 @@
|
||||
---
|
||||
name: vue-debug-guides
|
||||
description: Vue 3 debugging and error handling for runtime errors, warnings, async failures, and SSR/hydration issues. Use when diagnosing or fixing Vue issues.
|
||||
---
|
||||
|
||||
Vue 3 debugging and error handling for runtime issues, warnings, async failures, and hydration bugs.
|
||||
For development best practices and common gotchas, use `vue-best-practices`.
|
||||
|
||||
### Reactivity
|
||||
- Tracing unexpected re-renders and state updates → See [reactivity-debugging-hooks](reference/reactivity-debugging-hooks.md)
|
||||
- Ref values not updating due to missing .value access → See [ref-value-access](reference/ref-value-access.md)
|
||||
- State stops updating after destructuring reactive objects → See [reactive-destructuring](reference/reactive-destructuring.md)
|
||||
- Refs inside arrays, Maps, or Sets not unwrapping → See [refs-in-collections-need-value](reference/refs-in-collections-need-value.md)
|
||||
- Nested refs rendering as [object Object] in templates → See [template-ref-unwrapping-top-level](reference/template-ref-unwrapping-top-level.md)
|
||||
- Reactive proxy identity comparisons always return false → See [reactivity-proxy-identity-hazard](reference/reactivity-proxy-identity-hazard.md)
|
||||
- Third-party instances breaking when proxied → See [reactivity-markraw-for-non-reactive](reference/reactivity-markraw-for-non-reactive.md)
|
||||
- Watchers only firing once per tick unexpectedly → See [reactivity-same-tick-batching](reference/reactivity-same-tick-batching.md)
|
||||
|
||||
### Computed
|
||||
- Computed getter triggers mutations or requests unexpectedly → See [computed-no-side-effects](reference/computed-no-side-effects.md)
|
||||
- Mutating computed values causes changes to disappear → See [computed-return-value-readonly](reference/computed-return-value-readonly.md)
|
||||
- Computed value never updates after conditional logic → See [computed-conditional-dependencies](reference/computed-conditional-dependencies.md)
|
||||
- Sorting or reversing arrays breaks original state → See [computed-array-mutation](reference/computed-array-mutation.md)
|
||||
- Passing parameters to computed properties fails → See [computed-no-parameters](reference/computed-no-parameters.md)
|
||||
|
||||
### Watchers
|
||||
- Async operations overwriting with stale data → See [watch-async-cleanup](reference/watch-async-cleanup.md)
|
||||
- Creating watchers inside async callbacks → See [watch-async-creation-memory-leak](reference/watch-async-creation-memory-leak.md)
|
||||
- Watcher never triggers for reactive object properties → See [watch-reactive-property-getter](reference/watch-reactive-property-getter.md)
|
||||
- Async watchEffect misses dependencies after await → See [watcheffect-async-dependency-tracking](reference/watcheffect-async-dependency-tracking.md)
|
||||
- DOM reads are stale inside watcher callbacks → See [watch-flush-timing](reference/watch-flush-timing.md)
|
||||
- Deep watchers report identical old/new values → See [watch-deep-same-object-reference](reference/watch-deep-same-object-reference.md)
|
||||
- watchEffect runs before template refs update → See [watcheffect-flush-post-for-refs](reference/watcheffect-flush-post-for-refs.md)
|
||||
|
||||
### Components
|
||||
- Child component throws "component not found" error → See [local-components-not-in-descendants](reference/local-components-not-in-descendants.md)
|
||||
- Click listener doesn't fire on custom component → See [click-events-on-components](reference/click-events-on-components.md)
|
||||
- Parent can't access child ref data in script setup → See [component-ref-requires-defineexpose](reference/component-ref-requires-defineexpose.md)
|
||||
- HTML template parsing breaks Vue component syntax → See [in-dom-template-parsing-caveats](reference/in-dom-template-parsing-caveats.md)
|
||||
- Wrong component renders due to naming collisions → See [component-naming-conflicts](reference/component-naming-conflicts.md)
|
||||
- Parent styles don't apply to multi-root component → See [multi-root-component-class-attrs](reference/multi-root-component-class-attrs.md)
|
||||
|
||||
### Props & Emits
|
||||
- Variables referenced in defineProps cause errors → See [prop-defineprops-scope-limitation](reference/prop-defineprops-scope-limitation.md)
|
||||
- Component emits undeclared event causing warnings → See [declare-emits-for-documentation](reference/declare-emits-for-documentation.md)
|
||||
- defineEmits used inside function or conditional → See [defineEmits-must-be-top-level](reference/defineEmits-must-be-top-level.md)
|
||||
- defineEmits has both type and runtime arguments → See [defineEmits-no-runtime-and-type-mixed](reference/defineEmits-no-runtime-and-type-mixed.md)
|
||||
- Native event listeners not responding to clicks → See [native-event-collision-with-emits](reference/native-event-collision-with-emits.md)
|
||||
- Component event fires twice when clicking → See [undeclared-emits-double-firing](reference/undeclared-emits-double-firing.md)
|
||||
|
||||
### Templates
|
||||
- Getting template compilation errors with statements → See [template-expressions-restrictions](reference/template-expressions-restrictions.md)
|
||||
- "Cannot read property of undefined" runtime errors → See [v-if-null-check-order](reference/v-if-null-check-order.md)
|
||||
- Dynamic directive arguments not working properly → See [dynamic-argument-constraints](reference/dynamic-argument-constraints.md)
|
||||
- v-else elements rendering unconditionally always → See [v-else-must-follow-v-if](reference/v-else-must-follow-v-if.md)
|
||||
- Mixing v-if with v-for causes precedence bugs and migration breakage → See [no-v-if-with-v-for](reference/no-v-if-with-v-for.md)
|
||||
- Template function calls mutating state cause unpredictable re-render bugs → See [template-functions-no-side-effects](reference/template-functions-no-side-effects.md)
|
||||
- Child components in loops showing undefined data → See [v-for-component-props](reference/v-for-component-props.md)
|
||||
- Array order changing after sorting or reversing → See [v-for-computed-reverse-sort](reference/v-for-computed-reverse-sort.md)
|
||||
- List items disappearing or swapping state unexpectedly → See [v-for-key-attribute](reference/v-for-key-attribute.md)
|
||||
- Getting off-by-one errors with range iteration → See [v-for-range-starts-at-one](reference/v-for-range-starts-at-one.md)
|
||||
- v-show or v-else not working on template elements → See [v-show-template-limitation](reference/v-show-template-limitation.md)
|
||||
|
||||
### Template Refs
|
||||
- Ref becomes null when element is conditionally hidden → See [template-ref-null-with-v-if](reference/template-ref-null-with-v-if.md)
|
||||
- Ref array indices don't match data array in loops → See [template-ref-v-for-order](reference/template-ref-v-for-order.md)
|
||||
- Refactoring template ref names breaks silently in code → See [use-template-ref-vue35](reference/use-template-ref-vue35.md)
|
||||
|
||||
### Forms & v-model
|
||||
- Initial form values not showing when using v-model → See [v-model-ignores-html-attributes](reference/v-model-ignores-html-attributes.md)
|
||||
- Textarea content changes not updating the ref → See [textarea-no-interpolation](reference/textarea-no-interpolation.md)
|
||||
- iOS users cannot select dropdown first option → See [select-initial-value-ios-bug](reference/select-initial-value-ios-bug.md)
|
||||
- Parent and child components have different values → See [define-model-default-value-sync](reference/define-model-default-value-sync.md)
|
||||
- Object property changes not syncing to parent → See [definemodel-object-mutation-no-emit](reference/definemodel-object-mutation-no-emit.md)
|
||||
- Real-time search/validation broken for Chinese/Japanese input → See [v-model-ime-composition](reference/v-model-ime-composition.md)
|
||||
- Number input returns empty string instead of zero → See [v-model-number-modifier-behavior](reference/v-model-number-modifier-behavior.md)
|
||||
- Custom checkbox values not submitted in forms → See [checkbox-true-false-value-form-submission](reference/checkbox-true-false-value-form-submission.md)
|
||||
|
||||
### Events & Modifiers
|
||||
- Chaining multiple event modifiers produces unexpected results → See [event-modifier-order-matters](reference/event-modifier-order-matters.md)
|
||||
- Keyboard shortcuts don't fire with system modifier keys → See [keyup-modifier-timing](reference/keyup-modifier-timing.md)
|
||||
- Keyboard shortcuts fire with unintended modifier combinations → See [exact-modifier-for-precise-shortcuts](reference/exact-modifier-for-precise-shortcuts.md)
|
||||
- Combining passive and prevent modifiers breaks event behavior → See [no-passive-with-prevent](reference/no-passive-with-prevent.md)
|
||||
|
||||
### Lifecycle
|
||||
- Memory leaks from unremoved event listeners → See [cleanup-side-effects](reference/cleanup-side-effects.md)
|
||||
- DOM access fails before component mounts → See [lifecycle-dom-access-timing](reference/lifecycle-dom-access-timing.md)
|
||||
- DOM reads return stale values after state changes → See [dom-update-timing-nexttick](reference/dom-update-timing-nexttick.md)
|
||||
- SSR rendering differs from client hydration → See [lifecycle-ssr-awareness](reference/lifecycle-ssr-awareness.md)
|
||||
- Lifecycle hooks registered asynchronously never run → See [lifecycle-hooks-synchronous-registration](reference/lifecycle-hooks-synchronous-registration.md)
|
||||
|
||||
### Slots
|
||||
- Accessing child component data in slot content returns undefined values → See [slot-render-scope-parent-only](reference/slot-render-scope-parent-only.md)
|
||||
- Mixing named and scoped slots together causes compilation errors → See [slot-named-scoped-explicit-default](reference/slot-named-scoped-explicit-default.md)
|
||||
- Using v-slot on native HTML elements causes compilation errors → See [slot-v-slot-on-components-or-templates-only](reference/slot-v-slot-on-components-or-templates-only.md)
|
||||
- Unexpected content placement from implicit default slot behavior → See [slot-implicit-default-content](reference/slot-implicit-default-content.md)
|
||||
- Scoped slot props missing expected name property → See [slot-name-reserved-prop](reference/slot-name-reserved-prop.md)
|
||||
- Wrapper components breaking child slot functionality → See [slot-forwarding-to-child-components](reference/slot-forwarding-to-child-components.md)
|
||||
|
||||
### Provide/Inject
|
||||
- Calling provide after async operations fails silently → See [provide-inject-synchronous-setup](reference/provide-inject-synchronous-setup.md)
|
||||
- Tracing where provided values come from → See [provide-inject-debugging-challenges](reference/provide-inject-debugging-challenges.md)
|
||||
- Injected values not updating when provider changes → See [provide-inject-reactivity-not-automatic](reference/provide-inject-reactivity-not-automatic.md)
|
||||
- Multiple components share same default object → See [provide-inject-default-value-factory](reference/provide-inject-default-value-factory.md)
|
||||
|
||||
### Attrs
|
||||
- Both internal and fallthrough event handlers execute → See [attrs-event-listener-merging](reference/attrs-event-listener-merging.md)
|
||||
- Explicit attributes overwritten by fallthrough values → See [fallthrough-attrs-overwrite-vue3](reference/fallthrough-attrs-overwrite-vue3.md)
|
||||
- Attributes applying to wrong element in wrappers → See [inheritattrs-false-for-wrapper-components](reference/inheritattrs-false-for-wrapper-components.md)
|
||||
|
||||
### Composables
|
||||
- Composable called outside setup context or asynchronously → See [composable-call-location-restrictions](reference/composable-call-location-restrictions.md)
|
||||
- Composable reactive dependency not updating when input changes → See [composable-tovalue-inside-watcheffect](reference/composable-tovalue-inside-watcheffect.md)
|
||||
- Composable mutates external state unexpectedly → See [composable-avoid-hidden-side-effects](reference/composable-avoid-hidden-side-effects.md)
|
||||
- Destructuring composable returns breaks reactivity unexpectedly → See [composable-naming-return-pattern](reference/composable-naming-return-pattern.md)
|
||||
|
||||
### Composition API
|
||||
- Lifecycle hooks failing silently after async operations → See [composition-api-script-setup-async-context](reference/composition-api-script-setup-async-context.md)
|
||||
- Parent component refs unable to access exposed properties → See [define-expose-before-await](reference/define-expose-before-await.md)
|
||||
- Functional-programming patterns break expected Vue reactivity behavior → See [composition-api-not-functional-programming](reference/composition-api-not-functional-programming.md)
|
||||
- React Hook mental model causes incorrect Composition API usage → See [composition-api-vs-react-hooks-differences](reference/composition-api-vs-react-hooks-differences.md)
|
||||
|
||||
### Animation
|
||||
- Animations fail to trigger when DOM nodes are reused → See [animation-key-for-rerender](reference/animation-key-for-rerender.md)
|
||||
- TransitionGroup list updates feel laggy under load → See [animation-transitiongroup-performance](reference/animation-transitiongroup-performance.md)
|
||||
|
||||
### TypeScript
|
||||
- Mutable prop defaults leak state between component instances → See [ts-withdefaults-mutable-factory-function](reference/ts-withdefaults-mutable-factory-function.md)
|
||||
- reactive() generic typing causes ref unwrapping mismatches → See [ts-reactive-no-generic-argument](reference/ts-reactive-no-generic-argument.md)
|
||||
- Template refs throw null access errors before mount or after v-if unmount → See [ts-template-ref-null-handling](reference/ts-template-ref-null-handling.md)
|
||||
- Optional boolean props behave as false instead of undefined → See [ts-defineprops-boolean-default-false](reference/ts-defineprops-boolean-default-false.md)
|
||||
- Imported defineProps types fail with unresolvable or complex type references → See [ts-defineprops-imported-types-limitations](reference/ts-defineprops-imported-types-limitations.md)
|
||||
- Untyped DOM event handlers fail under strict TypeScript settings → See [ts-event-handler-explicit-typing](reference/ts-event-handler-explicit-typing.md)
|
||||
- Dynamic component refs trigger reactive component warnings → See [ts-shallowref-for-dynamic-components](reference/ts-shallowref-for-dynamic-components.md)
|
||||
- Union-typed template expressions fail type checks without narrowing → See [ts-template-type-casting](reference/ts-template-type-casting.md)
|
||||
|
||||
### Async Components
|
||||
- Route components misconfigured with defineAsyncComponent lazy loading → See [async-component-vue-router](reference/async-component-vue-router.md)
|
||||
- Network failures or timeouts loading components → See [async-component-error-handling](reference/async-component-error-handling.md)
|
||||
- Template refs undefined after component reactivation → See [async-component-keepalive-ref-issue](reference/async-component-keepalive-ref-issue.md)
|
||||
|
||||
### Render Functions
|
||||
- Render function output stays static after state changes → See [rendering-render-function-return-from-setup](reference/rendering-render-function-return-from-setup.md)
|
||||
- Reused vnode instances render incorrectly → See [render-function-vnodes-must-be-unique](reference/render-function-vnodes-must-be-unique.md)
|
||||
- String component names render as HTML elements → See [rendering-resolve-component-for-string-names](reference/rendering-resolve-component-for-string-names.md)
|
||||
- Accessing vnode internals breaks on Vue updates → See [render-function-avoid-internal-vnode-properties](reference/render-function-avoid-internal-vnode-properties.md)
|
||||
- Vue 2 render function patterns crash in Vue 3 → See [rendering-render-function-h-import-vue3](reference/rendering-render-function-h-import-vue3.md)
|
||||
- Slot content not rendering from h() → See [rendering-render-function-slots-as-functions](reference/rendering-render-function-slots-as-functions.md)
|
||||
|
||||
### KeepAlive
|
||||
- Child components mount twice with nested Vue Router routes → See [keepalive-router-nested-double-mount](reference/keepalive-router-nested-double-mount.md)
|
||||
- Memory grows when combining KeepAlive with Transition animations → See [keepalive-transition-memory-leak](reference/keepalive-transition-memory-leak.md)
|
||||
|
||||
### Transitions
|
||||
- JavaScript transition hooks hang without done callback → See [transition-js-hooks-done-callback](reference/transition-js-hooks-done-callback.md)
|
||||
- Move animations fail on inline list elements → See [transition-group-flip-inline-elements](reference/transition-group-flip-inline-elements.md)
|
||||
- List items jump instead of smoothly animating → See [transition-group-move-animation-position-absolute](reference/transition-group-move-animation-position-absolute.md)
|
||||
- Vue 2 to Vue 3 TransitionGroup wrapper changes break layout → See [transition-group-no-default-wrapper-vue3](reference/transition-group-no-default-wrapper-vue3.md)
|
||||
- Nested transitions cut off before finishing → See [transition-nested-duration](reference/transition-nested-duration.md)
|
||||
- Scoped styles stop working in reusable transition wrappers → See [transition-reusable-scoped-style](reference/transition-reusable-scoped-style.md)
|
||||
- RouterView transitions animate unexpectedly on first render → See [transition-router-view-appear](reference/transition-router-view-appear.md)
|
||||
- Mixing CSS transitions and animations causes timing issues → See [transition-type-when-mixed](reference/transition-type-when-mixed.md)
|
||||
- Cleanup hooks missed during rapid transition swaps → See [transition-unmount-hook-timing](reference/transition-unmount-hook-timing.md)
|
||||
|
||||
### Teleport
|
||||
- Teleport target element not found in DOM → See [teleport-target-must-exist](reference/teleport-target-must-exist.md)
|
||||
- Teleported content breaks SSR hydration → See [teleport-ssr-hydration](reference/teleport-ssr-hydration.md)
|
||||
- Scoped styles not applying to teleported content → See [teleport-scoped-styles-limitation](reference/teleport-scoped-styles-limitation.md)
|
||||
|
||||
### Suspense
|
||||
- Need to handle async errors from Suspense components → See [suspense-no-builtin-error-handling](reference/suspense-no-builtin-error-handling.md)
|
||||
- Using Suspense with server-side rendering → See [suspense-ssr-hydration-issues](reference/suspense-ssr-hydration-issues.md)
|
||||
- Async component loading/error UI ignored under Suspense → See [async-component-suspense-control](reference/async-component-suspense-control.md)
|
||||
|
||||
### SSR
|
||||
- HTML differs between server and client renders → See [ssr-hydration-mismatch-causes](reference/ssr-hydration-mismatch-causes.md)
|
||||
- User state leaks between requests from shared singleton stores → See [state-ssr-cross-request-pollution](reference/state-ssr-cross-request-pollution.md)
|
||||
- Browser-only APIs crash server rendering in universal code paths → See [ssr-platform-specific-apis](reference/ssr-platform-specific-apis.md)
|
||||
|
||||
### Performance
|
||||
- List children re-render unnecessarily because parent passes unstable props → See [perf-props-stability-update-optimization](reference/perf-props-stability-update-optimization.md)
|
||||
- Computed objects retrigger effects despite equivalent values → See [perf-computed-object-stability](reference/perf-computed-object-stability.md)
|
||||
|
||||
### SFC (Single File Components)
|
||||
- Trying to use named exports from component script blocks → See [sfc-named-exports-forbidden](reference/sfc-named-exports-forbidden.md)
|
||||
- Variables not updating in template after changes → See [sfc-script-setup-reactivity](reference/sfc-script-setup-reactivity.md)
|
||||
- Scoped styles not applying to child component elements → See [sfc-scoped-css-child-component-styling](reference/sfc-scoped-css-child-component-styling.md)
|
||||
- Scoped styles not applying to dynamic v-html content → See [sfc-scoped-css-dynamic-content](reference/sfc-scoped-css-dynamic-content.md)
|
||||
- Scoped styles not applying to slot content → See [sfc-scoped-css-slot-content](reference/sfc-scoped-css-slot-content.md)
|
||||
- Tailwind classes missing when built dynamically → See [tailwind-dynamic-class-generation](reference/tailwind-dynamic-class-generation.md)
|
||||
- Recursive components not rendering due to name conflicts → See [self-referencing-component-name](reference/self-referencing-component-name.md)
|
||||
|
||||
### Plugins
|
||||
- Debugging why global properties cause naming conflicts → See [plugin-global-properties-sparingly](reference/plugin-global-properties-sparingly.md)
|
||||
- Plugin not working or inject returns undefined → See [plugin-install-before-mount](reference/plugin-install-before-mount.md)
|
||||
- Plugin global properties are unavailable in setup-based components → See [plugin-prefer-provide-inject-over-global-properties](reference/plugin-prefer-provide-inject-over-global-properties.md)
|
||||
- Plugin type augmentation mistakes break ComponentCustomProperties typing → See [plugin-typescript-type-augmentation](reference/plugin-typescript-type-augmentation.md)
|
||||
|
||||
### App Configuration
|
||||
- App configuration methods not working after mount call → See [configure-app-before-mount](reference/configure-app-before-mount.md)
|
||||
- Chaining app config off mount() fails because mount returns component instance → See [mount-return-value](reference/mount-return-value.md)
|
||||
- require.context-based component auto-registration fails in Vite → See [dynamic-component-registration-vite](reference/dynamic-component-registration-vite.md)
|
||||
@@ -0,0 +1,160 @@
|
||||
---
|
||||
title: Use Key Attribute to Force Re-render Animations
|
||||
impact: MEDIUM
|
||||
impactDescription: Without key attributes, Vue reuses DOM elements and animation libraries like AutoAnimate cannot detect changes to animate
|
||||
type: gotcha
|
||||
tags: [vue3, animation, key, autoanimate, rerender, dom]
|
||||
---
|
||||
|
||||
# Use Key Attribute to Force Re-render Animations
|
||||
|
||||
**Impact: MEDIUM** - Vue optimizes performance by reusing DOM elements when possible. However, this optimization can prevent animation libraries (like AutoAnimate) from detecting changes, because the element is updated in place rather than re-created. Adding a `:key` attribute forces Vue to treat changed elements as new, triggering proper animations.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Add `:key` to elements that should animate when their content changes
|
||||
- [ ] Use unique, changing values for keys (not indices)
|
||||
- [ ] For route transitions, add `:key="$route.fullPath"` to `<router-view>`
|
||||
- [ ] Apply `v-auto-animate` to the parent element of keyed children
|
||||
|
||||
**Problematic Code:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- BAD: Text changes but no animation occurs -->
|
||||
<div v-auto-animate>
|
||||
<p>{{ message }}</p> <!-- No key - element is reused -->
|
||||
</div>
|
||||
|
||||
<!-- BAD: Image source changes but no animation -->
|
||||
<div v-auto-animate>
|
||||
<img :src="imageUrl" /> <!-- No key - element is reused -->
|
||||
</div>
|
||||
|
||||
<!-- BAD: Route changes don't animate -->
|
||||
<router-view v-auto-animate /> <!-- No key -->
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const message = ref('Hello')
|
||||
const imageUrl = ref('/images/photo1.jpg')
|
||||
|
||||
// Changing these won't trigger animations because
|
||||
// Vue updates the existing elements rather than replacing them
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct Code:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Key forces re-render, triggering animation -->
|
||||
<div v-auto-animate>
|
||||
<p :key="message">{{ message }}</p>
|
||||
</div>
|
||||
|
||||
<!-- GOOD: Image animates when source changes -->
|
||||
<div v-auto-animate>
|
||||
<img :key="imageUrl" :src="imageUrl" />
|
||||
</div>
|
||||
|
||||
<!-- GOOD: Route changes animate properly -->
|
||||
<router-view :key="$route.fullPath" v-auto-animate />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const message = ref('Hello')
|
||||
const imageUrl = ref('/images/photo1.jpg')
|
||||
|
||||
// Now changing these will trigger animations
|
||||
function updateMessage() {
|
||||
message.value = 'World' // Triggers enter animation for new <p>
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Why This Works
|
||||
|
||||
When Vue sees a `:key` change:
|
||||
1. It considers the old element and new element as different
|
||||
2. The old element is removed (triggering leave animation)
|
||||
3. A new element is created (triggering enter animation)
|
||||
|
||||
Without `:key`:
|
||||
1. Vue sees the same element type in the same position
|
||||
2. It updates the element's properties in place
|
||||
3. No DOM addition/removal occurs, so no animation triggers
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Animating Text Content Changes
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div v-auto-animate>
|
||||
<h1 :key="title">{{ title }}</h1>
|
||||
<p :key="description">{{ description }}</p>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Animating Dynamic Components
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div v-auto-animate>
|
||||
<component :is="currentComponent" :key="currentComponent" />
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Animating Route Transitions
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<router-view v-slot="{ Component, route }">
|
||||
<div v-auto-animate>
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</div>
|
||||
</router-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## With Vue's Built-in Transition
|
||||
|
||||
The same principle applies to Vue's `<Transition>` component:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Key triggers transition on content change -->
|
||||
<Transition name="fade" mode="out-in">
|
||||
<p :key="message">{{ message }}</p>
|
||||
</Transition>
|
||||
|
||||
<!-- GOOD: Different keys for conditional content -->
|
||||
<Transition name="fade" mode="out-in">
|
||||
<div v-if="isLoading" key="loading">Loading...</div>
|
||||
<div v-else key="content">{{ content }}</div>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Caution: Performance Implications
|
||||
|
||||
Using `:key` forces full component re-creation. For frequently changing data:
|
||||
- The entire component tree under the keyed element is destroyed and recreated
|
||||
- Any component state is lost
|
||||
- Consider whether the animation is worth the performance cost
|
||||
|
||||
```vue
|
||||
<!-- Be cautious with complex components -->
|
||||
<ComplexDashboard :key="refreshTrigger" />
|
||||
<!-- This destroys and recreates the entire dashboard! -->
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Animation Techniques](https://vuejs.org/guide/extras/animation.html)
|
||||
- [AutoAnimate with Vue](https://auto-animate.formkit.com/#usage-vue)
|
||||
- [Vue.js v-for with key](https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key)
|
||||
@@ -0,0 +1,241 @@
|
||||
---
|
||||
title: TransitionGroup Performance with Large Lists and CSS Frameworks
|
||||
impact: MEDIUM
|
||||
impactDescription: TransitionGroup can cause noticeable DOM update lag when animating list changes, especially with CSS frameworks
|
||||
type: gotcha
|
||||
tags: [vue3, transition-group, animation, performance, list, css-framework]
|
||||
---
|
||||
|
||||
# TransitionGroup Performance with Large Lists and CSS Frameworks
|
||||
|
||||
**Impact: MEDIUM** - Vue's `<TransitionGroup>` can experience significant DOM update lag when animating list changes, particularly when:
|
||||
- Using CSS frameworks (Tailwind, Bootstrap, etc.)
|
||||
- Performing array operations like `slice()` that change multiple items
|
||||
- Working with larger lists
|
||||
|
||||
Without TransitionGroup, DOM updates occur instantly. With it, there can be noticeable delay before the UI reflects changes.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] For frequently updated lists, consider if transition animations are necessary
|
||||
- [ ] Use CSS `content-visibility: auto` for long lists to reduce render cost
|
||||
- [ ] Minimize CSS framework classes on list items during transitions
|
||||
- [ ] Consider virtual scrolling for very large animated lists
|
||||
- [ ] Profile with Vue DevTools to identify transition bottlenecks
|
||||
|
||||
**Problematic Pattern:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- Potentially slow with large lists or complex CSS -->
|
||||
<TransitionGroup name="list" tag="ul">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="p-4 m-2 rounded-lg shadow-md bg-gradient-to-r from-blue-500 to-purple-600
|
||||
hover:shadow-lg transition-all duration-300 ease-in-out transform hover:scale-105
|
||||
border border-gray-200 flex items-center justify-between"
|
||||
>
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const items = ref([/* many items */])
|
||||
|
||||
// Operations like slice can cause visible lag
|
||||
function removeItems() {
|
||||
items.value = items.value.slice(5) // May lag with TransitionGroup
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.list-move,
|
||||
.list-enter-active,
|
||||
.list-leave-active {
|
||||
transition: all 0.5s ease;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
**Optimized Approach:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- Simpler classes, shorter transitions -->
|
||||
<TransitionGroup name="list" tag="ul" class="relative">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="list-item"
|
||||
>
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</TransitionGroup>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([/* items */])
|
||||
|
||||
// For large batch operations, consider disabling animations temporarily
|
||||
const isAnimating = ref(true)
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* Keep transition CSS simple and specific */
|
||||
.list-item {
|
||||
/* Minimal styles during animation */
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.list-move {
|
||||
transition: transform 0.3s ease; /* Shorter duration */
|
||||
}
|
||||
|
||||
.list-enter-active,
|
||||
.list-leave-active {
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.list-enter-from,
|
||||
.list-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateX(-20px);
|
||||
}
|
||||
|
||||
/* Use will-change sparingly */
|
||||
.list-enter-active {
|
||||
will-change: opacity, transform;
|
||||
}
|
||||
|
||||
/* Absolute positioning for leaving elements prevents layout thrashing */
|
||||
.list-leave-active {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Performance Optimization Strategies
|
||||
|
||||
### 1. Skip Animations for Bulk Operations
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<TransitionGroup v-if="animationsEnabled" name="list" tag="ul">
|
||||
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
|
||||
</TransitionGroup>
|
||||
|
||||
<!-- Instant update without animations -->
|
||||
<ul v-else>
|
||||
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, nextTick } from 'vue'
|
||||
|
||||
const animationsEnabled = ref(true)
|
||||
|
||||
async function bulkUpdate(newItems) {
|
||||
// Disable animations for bulk operations
|
||||
animationsEnabled.value = false
|
||||
items.value = newItems
|
||||
await nextTick()
|
||||
animationsEnabled.value = true
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2. Virtual Scrolling for Large Lists
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Use a virtual list library for large datasets -->
|
||||
<RecycleScroller
|
||||
:items="items"
|
||||
:item-size="50"
|
||||
key-field="id"
|
||||
v-slot="{ item }"
|
||||
>
|
||||
<div class="list-item">{{ item.name }}</div>
|
||||
</RecycleScroller>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { RecycleScroller } from 'vue-virtual-scroller'
|
||||
</script>
|
||||
```
|
||||
|
||||
### 3. Reduce CSS Complexity During Transitions
|
||||
|
||||
```vue
|
||||
<style>
|
||||
/* Move complex styles to a stable wrapper */
|
||||
.list-item-wrapper {
|
||||
@apply p-4 m-2 rounded-lg shadow-md bg-gradient-to-r from-blue-500 to-purple-600;
|
||||
}
|
||||
|
||||
/* Keep animated element styles minimal */
|
||||
.list-item {
|
||||
/* Only essential layout styles */
|
||||
}
|
||||
|
||||
.list-move,
|
||||
.list-enter-active,
|
||||
.list-leave-active {
|
||||
/* Only animate transform/opacity - GPU accelerated */
|
||||
transition: transform 0.3s ease, opacity 0.3s ease;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### 4. Use CSS content-visibility
|
||||
|
||||
```css
|
||||
/* For very long lists, defer rendering of off-screen items */
|
||||
.list-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 50px; /* Estimated height */
|
||||
}
|
||||
```
|
||||
|
||||
## When to Avoid TransitionGroup
|
||||
|
||||
Consider alternatives when:
|
||||
- List updates are frequent (real-time data)
|
||||
- List contains 100+ items
|
||||
- Items have complex CSS or nested components
|
||||
- Performance is critical (mobile, low-end devices)
|
||||
|
||||
```vue
|
||||
<!-- Simple alternative: CSS-only animations on individual items -->
|
||||
<ul>
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="animate-in"
|
||||
>
|
||||
{{ item.name }}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<style>
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(-10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.animate-in {
|
||||
animation: fadeIn 0.3s ease forwards;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js TransitionGroup](https://vuejs.org/guide/built-ins/transition-group.html)
|
||||
- [GitHub Issue: transition-group DOM update lag](https://github.com/vuejs/vue/issues/5845)
|
||||
- [Vue Virtual Scroller](https://github.com/Akryum/vue-virtual-scroller)
|
||||
@@ -0,0 +1,115 @@
|
||||
# Async Component Error Handling
|
||||
|
||||
## Rule
|
||||
|
||||
Always configure error handling for async components using `errorComponent` and/or `onError` callback. Without proper error handling, failed component loads can leave the UI in an undefined state with no user feedback.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
Network failures, timeouts, and server errors are common in production. Without error handling, users see blank spaces or broken UIs with no indication of what went wrong or how to recover.
|
||||
|
||||
## Bad Code
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
// No error handling - fails silently
|
||||
const AsyncWidget = defineAsyncComponent(() =>
|
||||
import('./Widget.vue')
|
||||
)
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
// isLoading never becomes false on error - infinite spinner
|
||||
const isLoading = ref(true)
|
||||
const Widget = defineAsyncComponent({
|
||||
loader: () => import('./Widget.vue').finally(() => {
|
||||
isLoading.value = false // Only runs on success
|
||||
})
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Good Code
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import LoadingSpinner from './LoadingSpinner.vue'
|
||||
import ErrorDisplay from './ErrorDisplay.vue'
|
||||
|
||||
const AsyncWidget = defineAsyncComponent({
|
||||
loader: () => import('./Widget.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
errorComponent: ErrorDisplay,
|
||||
delay: 200, // Prevent loading flicker
|
||||
timeout: 10000 // Show error after 10 seconds
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
// With retry logic using onError
|
||||
const AsyncWidget = defineAsyncComponent({
|
||||
loader: () => import('./Widget.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
errorComponent: ErrorDisplay,
|
||||
onError(error, retry, fail, attempts) {
|
||||
if (attempts <= 3) {
|
||||
// Retry up to 3 times
|
||||
retry()
|
||||
} else {
|
||||
// Give up and show error component
|
||||
fail()
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
// Fallback component pattern - catch in loader
|
||||
const AsyncWidget = defineAsyncComponent(() =>
|
||||
import('./Widget.vue').catch(() => import('./WidgetFallback.vue'))
|
||||
)
|
||||
</script>
|
||||
```
|
||||
|
||||
## onError Callback Parameters
|
||||
|
||||
The `onError` callback receives four arguments:
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `error` | `Error` | The error that caused the load to fail |
|
||||
| `retry` | `Function` | Call to retry loading the component |
|
||||
| `fail` | `Function` | Call to give up and show errorComponent |
|
||||
| `attempts` | `number` | Number of load attempts so far |
|
||||
|
||||
## Key Points
|
||||
|
||||
1. Always provide an `errorComponent` for production applications
|
||||
2. Use `timeout` to prevent indefinite loading states
|
||||
3. Consider retry logic with `onError` for transient network issues
|
||||
4. The `delay` option (default 200ms) prevents loading flicker on fast networks
|
||||
5. Use the fallback pattern (`.catch()` in loader) when you want a seamless degradation
|
||||
|
||||
## SSR Warning
|
||||
|
||||
Using `onError` with SSR can cause issues in some configurations, potentially leading to infinite loading. Test thoroughly in SSR environments.
|
||||
|
||||
## References
|
||||
|
||||
- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async)
|
||||
- [Handling Async Components' loading errors](https://awad.dev/blog/handling-async-component-loading-errors/)
|
||||
@@ -0,0 +1,112 @@
|
||||
# Async Components with keep-alive Ref Issues
|
||||
|
||||
## Rule
|
||||
|
||||
When using `<keep-alive>`, `<component>`, and `defineAsyncComponent` together, be aware that template refs can become undefined when the component is re-activated after being deactivated.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
This is a known Vue issue where the ref binding works correctly on first activation but becomes undefined on subsequent activations. This can cause runtime errors when trying to access component methods or properties through refs.
|
||||
|
||||
## Problem Scenario
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, defineAsyncComponent } from 'vue'
|
||||
|
||||
const AsyncWidget = defineAsyncComponent(() =>
|
||||
import('./Widget.vue')
|
||||
)
|
||||
|
||||
const currentComponent = ref(AsyncWidget)
|
||||
const widgetRef = ref(null)
|
||||
|
||||
function callWidgetMethod() {
|
||||
// May be undefined after component reactivation!
|
||||
widgetRef.value?.doSomething()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<keep-alive>
|
||||
<component :is="currentComponent" ref="widgetRef" />
|
||||
</keep-alive>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Workarounds
|
||||
|
||||
### Option 1: Use onActivated to re-establish ref access
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, defineAsyncComponent, onActivated, nextTick } from 'vue'
|
||||
|
||||
const AsyncWidget = defineAsyncComponent(() =>
|
||||
import('./Widget.vue')
|
||||
)
|
||||
|
||||
const currentComponent = ref(AsyncWidget)
|
||||
const widgetRef = ref(null)
|
||||
|
||||
// Use a computed or method that waits for ref to be available
|
||||
async function callWidgetMethod() {
|
||||
await nextTick()
|
||||
if (widgetRef.value) {
|
||||
widgetRef.value.doSomething()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### Option 2: Avoid mixing all three patterns
|
||||
|
||||
If possible, use one of these alternatives:
|
||||
|
||||
```vue
|
||||
<!-- Option A: Don't use keep-alive with async components -->
|
||||
<template>
|
||||
<component :is="currentComponent" ref="widgetRef" />
|
||||
</template>
|
||||
|
||||
<!-- Option B: Use static component with keep-alive -->
|
||||
<script setup>
|
||||
import Widget from './Widget.vue' // Regular import
|
||||
</script>
|
||||
<template>
|
||||
<keep-alive>
|
||||
<component :is="Widget" ref="widgetRef" />
|
||||
</keep-alive>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 3: Use provide/inject instead of refs
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<script setup>
|
||||
import { provide, ref } from 'vue'
|
||||
|
||||
const sharedState = ref({ /* shared data */ })
|
||||
provide('widgetState', sharedState)
|
||||
</script>
|
||||
|
||||
<!-- Widget.vue (async component) -->
|
||||
<script setup>
|
||||
import { inject } from 'vue'
|
||||
const widgetState = inject('widgetState')
|
||||
</script>
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
1. This is a known issue when combining `<keep-alive>`, `<component :is>`, and `defineAsyncComponent`
|
||||
2. Refs may become undefined after component deactivation/reactivation
|
||||
3. Use `nextTick` and null checks when accessing refs
|
||||
4. Consider alternative patterns like provide/inject for cross-component communication
|
||||
5. Test thoroughly when using this combination
|
||||
|
||||
## References
|
||||
|
||||
- [Vue.js GitHub Discussion #11334](https://github.com/orgs/vuejs/discussions/11334)
|
||||
- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async)
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
title: Suspense Overrides Async Component Loading and Error Options
|
||||
impact: MEDIUM
|
||||
impactDescription: Async component loading/error options are ignored under a parent Suspense, leading to missing spinners and error UIs
|
||||
type: gotcha
|
||||
tags: [vue3, suspense, async-components, loading, error-handling]
|
||||
---
|
||||
|
||||
# Suspense Overrides Async Component Loading and Error Options
|
||||
|
||||
**Impact: MEDIUM** - When an async component renders inside a parent `<Suspense>`, its `loadingComponent`, `errorComponent`, `delay`, and `timeout` options do not run. The parent Suspense controls loading and error UX instead.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Confirm whether the async component is inside a `<Suspense>` boundary
|
||||
- [ ] Use `suspensible: false` when the component must manage its own loading/error UI
|
||||
- [ ] Or move loading/error UI to the parent `<Suspense>` fallback and an error boundary (`onErrorCaptured`)
|
||||
- [ ] Provide a retry path for failed loads
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
const AsyncDashboard = defineAsyncComponent({
|
||||
loader: () => import('./Dashboard.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
errorComponent: ErrorDisplay,
|
||||
timeout: 3000
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Suspense>
|
||||
<AsyncDashboard />
|
||||
<template #fallback>Loading...</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct (component handles its own states):**
|
||||
```vue
|
||||
<script setup>
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
const AsyncDashboard = defineAsyncComponent({
|
||||
loader: () => import('./Dashboard.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
errorComponent: ErrorDisplay,
|
||||
timeout: 3000,
|
||||
suspensible: false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AsyncDashboard />
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct (parent Suspense owns loading/error UI):**
|
||||
```vue
|
||||
<script setup>
|
||||
import { onErrorCaptured, ref } from 'vue'
|
||||
import AsyncDashboard from './AsyncDashboard.vue'
|
||||
|
||||
const error = ref(null)
|
||||
|
||||
onErrorCaptured((err) => {
|
||||
error.value = err
|
||||
return false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ErrorDisplay v-if="error" :error="error" />
|
||||
|
||||
<Suspense v-else>
|
||||
<AsyncDashboard />
|
||||
<template #fallback>
|
||||
<LoadingSpinner />
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
@@ -0,0 +1,109 @@
|
||||
# Do Not Use defineAsyncComponent with Vue Router
|
||||
|
||||
## Rule
|
||||
|
||||
Never use `defineAsyncComponent` when configuring Vue Router route components. Vue Router has its own lazy loading mechanism using dynamic imports directly.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
Vue Router's lazy loading is specifically designed for route-level code splitting. Using `defineAsyncComponent` for routes adds unnecessary overhead and can cause unexpected behavior with navigation guards, loading states, and route transitions.
|
||||
|
||||
## Bad Code
|
||||
|
||||
```javascript
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
{
|
||||
path: '/dashboard',
|
||||
// WRONG: Don't use defineAsyncComponent here
|
||||
component: defineAsyncComponent(() =>
|
||||
import('./views/Dashboard.vue')
|
||||
)
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
// WRONG: This also won't work as expected
|
||||
component: defineAsyncComponent({
|
||||
loader: () => import('./views/Profile.vue'),
|
||||
loadingComponent: LoadingSpinner
|
||||
})
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
## Good Code
|
||||
|
||||
```javascript
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
{
|
||||
path: '/dashboard',
|
||||
// CORRECT: Use dynamic import directly
|
||||
component: () => import('./views/Dashboard.vue')
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
// CORRECT: Simple arrow function with import
|
||||
component: () => import('./views/Profile.vue')
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
## Handling Loading States with Vue Router
|
||||
|
||||
For route-level loading states, use Vue Router's navigation guards or a global loading indicator:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const router = useRouter()
|
||||
const isLoading = ref(false)
|
||||
|
||||
router.beforeEach(() => {
|
||||
isLoading.value = true
|
||||
})
|
||||
|
||||
router.afterEach(() => {
|
||||
isLoading.value = false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<LoadingBar v-if="isLoading" />
|
||||
<RouterView />
|
||||
</template>
|
||||
```
|
||||
|
||||
## When to Use defineAsyncComponent
|
||||
|
||||
Use `defineAsyncComponent` for:
|
||||
- Components loaded conditionally within a page
|
||||
- Heavy components that aren't always needed
|
||||
- Modal dialogs or panels that load on demand
|
||||
|
||||
Use Vue Router's lazy loading for:
|
||||
- Route-level components (views/pages)
|
||||
- Any component configured in route definitions
|
||||
|
||||
## Key Points
|
||||
|
||||
1. Vue Router and `defineAsyncComponent` are separate lazy loading mechanisms
|
||||
2. Route components should use direct dynamic imports: `() => import('./View.vue')`
|
||||
3. Use navigation guards for route-level loading indicators
|
||||
4. `defineAsyncComponent` is for component-level lazy loading within pages
|
||||
|
||||
## References
|
||||
|
||||
- [Vue Router Lazy Loading Routes](https://router.vuejs.org/guide/advanced/lazy-loading.html)
|
||||
- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async)
|
||||
@@ -0,0 +1,205 @@
|
||||
# Fallthrough Event Listeners Are Additive
|
||||
|
||||
## Rule
|
||||
|
||||
When an event listener is passed to a component as a fallthrough attribute, it is added to the root element's existing listeners of the same type - both will trigger. This is different from props where values are replaced. Be aware that both the component's internal handler and the parent's handler will execute.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
- Developers may expect event listeners to override like props
|
||||
- Both handlers execute, which can cause double submissions, duplicate API calls
|
||||
- Order of execution: internal handler first, then fallthrough handler
|
||||
- This is actually useful for composition but can cause bugs if unexpected
|
||||
|
||||
## Bad Code
|
||||
|
||||
```vue
|
||||
<!-- BaseButton.vue - Potential double-action bug -->
|
||||
<template>
|
||||
<button @click="internalClick">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
const emit = defineEmits(['action'])
|
||||
|
||||
function internalClick() {
|
||||
// This runs first
|
||||
emit('action')
|
||||
console.log('Internal click handler')
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<BaseButton @click="parentClick">Submit</BaseButton>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
function parentClick() {
|
||||
// This ALSO runs (after internal)
|
||||
submitForm() // Might cause double submission!
|
||||
console.log('Parent click handler')
|
||||
}
|
||||
</script>
|
||||
|
||||
<!--
|
||||
RESULT: Both handlers fire!
|
||||
Console output:
|
||||
1. "Internal click handler"
|
||||
2. "Parent click handler"
|
||||
|
||||
If both trigger API calls, you get duplicate requests
|
||||
-->
|
||||
```
|
||||
|
||||
## Good Code
|
||||
|
||||
### Option 1: Prevent fallthrough with inheritAttrs: false
|
||||
|
||||
```vue
|
||||
<!-- BaseButton.vue - Control event handling explicitly -->
|
||||
<script setup>
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
|
||||
const emit = defineEmits(['click'])
|
||||
|
||||
function handleClick(event) {
|
||||
// Component controls all click behavior
|
||||
console.log('Handled internally')
|
||||
emit('click', event) // Explicitly forward if needed
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleClick">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 2: Document the additive behavior
|
||||
|
||||
```vue
|
||||
<!-- BaseButton.vue - Design for composition -->
|
||||
<script setup>
|
||||
/**
|
||||
* BaseButton - A composable button component
|
||||
*
|
||||
* Note: Click handlers passed to this component are ADDITIVE.
|
||||
* The internal handler runs first, then any parent @click handler.
|
||||
* Use @action event if you only want to respond to the action.
|
||||
*/
|
||||
const emit = defineEmits(['action'])
|
||||
|
||||
function internalClick() {
|
||||
// Internal logic (e.g., ripple effect, analytics)
|
||||
emit('action')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="internalClick">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<!-- Parent.vue - Use the custom event instead -->
|
||||
<template>
|
||||
<!-- Use @action, not @click, to avoid double handling -->
|
||||
<BaseButton @action="handleAction">Submit</BaseButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 3: Use stopPropagation if needed
|
||||
|
||||
```vue
|
||||
<!-- BaseButton.vue - Stop event propagation when needed -->
|
||||
<script setup>
|
||||
const props = defineProps({
|
||||
stopPropagation: Boolean
|
||||
})
|
||||
|
||||
function handleClick(event) {
|
||||
if (props.stopPropagation) {
|
||||
event.stopPropagation()
|
||||
}
|
||||
// Internal handling...
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleClick">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Using Additive Behavior Intentionally
|
||||
|
||||
The additive behavior can be useful for extending functionality:
|
||||
|
||||
```vue
|
||||
<!-- EnhancedButton.vue - Leveraging additive listeners -->
|
||||
<template>
|
||||
<button
|
||||
@click="trackClick"
|
||||
@focus="trackFocus"
|
||||
>
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
function trackClick() {
|
||||
analytics.track('button_click')
|
||||
// Parent's @click will also run - that's intentional!
|
||||
}
|
||||
|
||||
function trackFocus() {
|
||||
analytics.track('button_focus')
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<!-- Both analytics AND form submission happen -->
|
||||
<EnhancedButton @click="submitForm">Submit</EnhancedButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Execution Order
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// Component
|
||||
function componentHandler() {
|
||||
console.log('1. Component handler (first)')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="componentHandler">Click</button>
|
||||
</template>
|
||||
|
||||
<!-- Parent passes @click -->
|
||||
<!-- Execution order:
|
||||
1. componentHandler (defined in component)
|
||||
2. parentHandler (passed as fallthrough)
|
||||
-->
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **For UI components**: Use `inheritAttrs: false` and emit custom events
|
||||
2. **For HOCs/wrappers**: Document that listeners are additive
|
||||
3. **For analytics/tracking**: Leverage additive behavior intentionally
|
||||
4. **Avoid side effects**: Don't assume your handler is the only one running
|
||||
|
||||
## References
|
||||
|
||||
- [Fallthrough Attributes - v-on Listener Inheritance](https://vuejs.org/guide/components/attrs.html#v-on-listener-inheritance)
|
||||
- [Component Events](https://vuejs.org/guide/components/events.html)
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
title: Checkbox true-value/false-value Not Submitted in Forms
|
||||
impact: MEDIUM
|
||||
impactDescription: true-value and false-value attributes don't affect form submission - unchecked boxes send nothing
|
||||
type: capability
|
||||
tags: [vue3, v-model, forms, checkbox, form-submission]
|
||||
---
|
||||
|
||||
# Checkbox true-value/false-value Not Submitted in Forms
|
||||
|
||||
**Impact: MEDIUM** - Vue's `true-value` and `false-value` attributes only affect the JavaScript binding, NOT the actual form submission. Unchecked checkboxes are never included in form submissions by browsers, regardless of `false-value`.
|
||||
|
||||
This is a browser limitation, not a Vue issue. If you need to submit one of two values (like "yes"/"no" or "active"/"inactive"), use radio buttons instead of a checkbox.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Don't rely on `false-value` for form submissions - it won't be sent
|
||||
- [ ] Use radio buttons when you need to submit one of exactly two values
|
||||
- [ ] Remember `true-value`/`false-value` are for JavaScript state only
|
||||
- [ ] For form submissions with custom values, handle the transformation server-side or in submit handler
|
||||
|
||||
**Problem - false-value not submitted:**
|
||||
```html
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const status = ref('no') // JavaScript value works correctly
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form action="/api/update" method="POST">
|
||||
<!-- PROBLEM: When unchecked, nothing is submitted for this field -->
|
||||
<!-- Server receives no "status" field at all, not "no" -->
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="status"
|
||||
true-value="yes"
|
||||
false-value="no"
|
||||
name="status"
|
||||
>
|
||||
<label>Active</label>
|
||||
|
||||
<!-- status.value correctly shows "yes" or "no" in Vue -->
|
||||
<!-- But form submission only sends "status=yes" when checked -->
|
||||
<!-- When unchecked, "status" field is completely missing -->
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Solution 1 - Use radio buttons for two-value submission:**
|
||||
```html
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const status = ref('no')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form action="/api/update" method="POST">
|
||||
<!-- CORRECT: Radio buttons always submit a value -->
|
||||
<label>
|
||||
<input type="radio" v-model="status" value="yes" name="status">
|
||||
Active
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" v-model="status" value="no" name="status">
|
||||
Inactive
|
||||
</label>
|
||||
|
||||
<!-- Form always submits "status=yes" or "status=no" -->
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Solution 2 - Handle in submit handler (for SPA/AJAX):**
|
||||
```html
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const isActive = ref(false)
|
||||
|
||||
async function submitForm() {
|
||||
// Transform checkbox state to desired value before sending
|
||||
const payload = {
|
||||
status: isActive.value ? 'yes' : 'no'
|
||||
}
|
||||
|
||||
await fetch('/api/update', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- For AJAX submission, checkbox is fine - transform in handler -->
|
||||
<input type="checkbox" v-model="isActive">
|
||||
<label>Active</label>
|
||||
|
||||
<button @click="submitForm">Save</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Solution 3 - Hidden input fallback:**
|
||||
```html
|
||||
<template>
|
||||
<form action="/api/update" method="POST">
|
||||
<!-- Hidden input provides fallback value -->
|
||||
<input type="hidden" name="status" value="no">
|
||||
<!-- Checkbox overrides with "yes" when checked -->
|
||||
<input type="checkbox" name="status" value="yes" v-model="isActive">
|
||||
<label>Active</label>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Form Input Bindings - Checkbox](https://vuejs.org/guide/essentials/forms.html#checkbox)
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
title: Clean Up Event Listeners and Intervals in onUnmounted
|
||||
impact: HIGH
|
||||
impactDescription: Failing to clean up side effects causes memory leaks and ghost event handlers
|
||||
type: capability
|
||||
tags: [vue3, lifecycle, memory-leak, event-listeners, intervals, cleanup]
|
||||
---
|
||||
|
||||
# Clean Up Event Listeners and Intervals in onUnmounted
|
||||
|
||||
**Impact: HIGH** - Failing to clean up event listeners, intervals, timeouts, and subscriptions when a component unmounts causes memory leaks and ghost handlers that continue running, leading to performance degradation and subtle bugs in Single Page Applications.
|
||||
|
||||
When using custom events, timers, WebSocket connections, or third-party libraries, always clean up in `onUnmounted` (Composition API) or `unmounted` (Options API).
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Track all addEventListener calls and remove them in onUnmounted
|
||||
- [ ] Clear all setInterval and setTimeout calls in onUnmounted
|
||||
- [ ] Unsubscribe from external event emitters and observables
|
||||
- [ ] Disconnect WebSocket connections and third-party library instances
|
||||
- [ ] Use `onBeforeUnmount` if cleanup must happen before DOM removal
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// Composition API - WRONG: No cleanup
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
onMounted(() => {
|
||||
// These keep running after component unmounts!
|
||||
window.addEventListener('resize', handleResize)
|
||||
setInterval(pollServer, 5000)
|
||||
socket.on('message', handleMessage)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Options API - WRONG: No cleanup
|
||||
export default {
|
||||
mounted() {
|
||||
window.addEventListener('scroll', this.handleScroll)
|
||||
this.timer = setInterval(this.refresh, 10000)
|
||||
}
|
||||
// Component unmounts, but listeners and timers persist!
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// Composition API - CORRECT: Proper cleanup
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const intervalId = ref(null)
|
||||
|
||||
const handleResize = () => {
|
||||
// handle resize
|
||||
}
|
||||
|
||||
const handleMessage = (msg) => {
|
||||
// handle message
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('resize', handleResize)
|
||||
intervalId.value = setInterval(pollServer, 5000)
|
||||
socket.on('message', handleMessage)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
// Clean up everything!
|
||||
window.removeEventListener('resize', handleResize)
|
||||
|
||||
if (intervalId.value) {
|
||||
clearInterval(intervalId.value)
|
||||
}
|
||||
|
||||
socket.off('message', handleMessage)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Options API - CORRECT: Proper cleanup
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
timer: null
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
window.addEventListener('scroll', this.handleScroll)
|
||||
this.timer = setInterval(this.refresh, 10000)
|
||||
},
|
||||
unmounted() {
|
||||
window.removeEventListener('scroll', this.handleScroll)
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer)
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
handleScroll() { /* ... */ },
|
||||
refresh() { /* ... */ }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Using Composable Pattern for Auto-Cleanup
|
||||
|
||||
```javascript
|
||||
// Reusable composable with automatic cleanup
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
|
||||
export function useEventListener(target, event, handler) {
|
||||
onMounted(() => {
|
||||
target.addEventListener(event, handler)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
target.removeEventListener(event, handler)
|
||||
})
|
||||
}
|
||||
|
||||
export function useInterval(callback, delay) {
|
||||
let intervalId = null
|
||||
|
||||
onMounted(() => {
|
||||
intervalId = setInterval(callback, delay)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (intervalId) clearInterval(intervalId)
|
||||
})
|
||||
}
|
||||
|
||||
// Usage - cleanup is automatic
|
||||
import { useEventListener, useInterval } from './composables'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
useEventListener(window, 'resize', handleResize)
|
||||
useInterval(pollServer, 5000)
|
||||
// No manual cleanup needed!
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## VueUse Alternative
|
||||
|
||||
```javascript
|
||||
// VueUse provides cleanup-aware composables
|
||||
import { useEventListener, useIntervalFn } from '@vueuse/core'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
// Automatically cleaned up on unmount
|
||||
useEventListener(window, 'resize', handleResize)
|
||||
|
||||
const { pause, resume } = useIntervalFn(pollServer, 5000)
|
||||
// Also provides pause/resume controls
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html)
|
||||
- [VueUse - useEventListener](https://vueuse.org/core/useEventListener/)
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
title: Click Events on Custom Components Require Emit or Fallthrough
|
||||
impact: HIGH
|
||||
impactDescription: Native click events on custom components won't work without proper emit declaration or attribute fallthrough
|
||||
type: gotcha
|
||||
tags: [vue3, events, components, emit, click, migration]
|
||||
---
|
||||
|
||||
# Click Events on Custom Components Require Emit or Fallthrough
|
||||
|
||||
**Impact: HIGH** - Unlike native HTML elements, custom Vue components don't automatically forward native DOM events like `click`. You must either emit the event explicitly, rely on attribute fallthrough to a single root element, or use the `.native` modifier (Vue 2 only, removed in Vue 3). This is a common source of confusion and migration issues.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Declare emitted events using `defineEmits` in child components
|
||||
- [ ] Emit click events from child component when needed
|
||||
- [ ] Understand that single-root components automatically forward attrs to root
|
||||
- [ ] Remove `.native` modifier when migrating from Vue 2 to Vue 3
|
||||
- [ ] For multi-root components, explicitly bind `$attrs` or emit events
|
||||
|
||||
**Incorrect:**
|
||||
```html
|
||||
<!-- WRONG: Expecting native click to work on custom component -->
|
||||
<template>
|
||||
<MyButton @click="handleClick">Click me</MyButton>
|
||||
<!-- This may not work as expected! -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Vue 2 .native modifier doesn't exist in Vue 3 -->
|
||||
<template>
|
||||
<MyButton @click.native="handleClick">Click me</MyButton>
|
||||
<!-- Error in Vue 3: .native modifier removed -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Multi-root component with no attr binding -->
|
||||
<!-- MyButton.vue -->
|
||||
<template>
|
||||
<span>Icon</span>
|
||||
<button>{{ label }}</button>
|
||||
<!-- No root element to receive click! -->
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- CORRECT: Child component emits the click event -->
|
||||
<!-- MyButton.vue -->
|
||||
<template>
|
||||
<button @click="$emit('click', $event)">
|
||||
<slot></slot>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineEmits(['click'])
|
||||
</script>
|
||||
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<MyButton @click="handleClick">Click me</MyButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Single root element with automatic fallthrough -->
|
||||
<!-- MyButton.vue -->
|
||||
<template>
|
||||
<button>
|
||||
<slot></slot>
|
||||
</button>
|
||||
<!-- @click from parent automatically falls through to button -->
|
||||
</template>
|
||||
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<MyButton @click="handleClick">Click me</MyButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Multi-root component with explicit $attrs binding -->
|
||||
<!-- MyButton.vue -->
|
||||
<template>
|
||||
<span>Icon</span>
|
||||
<button v-bind="$attrs">
|
||||
<slot></slot>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Component Events Don't Bubble
|
||||
|
||||
```javascript
|
||||
// Important: Component-emitted events do NOT bubble
|
||||
// You can only listen to events from direct children
|
||||
|
||||
// WRONG: Trying to catch grandchild events
|
||||
<GrandParent @child-event="handle"> <!-- Won't receive! -->
|
||||
<Parent>
|
||||
<Child @click="$emit('child-event')" />
|
||||
</Parent>
|
||||
</GrandParent>
|
||||
|
||||
// CORRECT: Each level must relay the event
|
||||
<GrandParent @child-event="handle">
|
||||
<Parent @child-event="$emit('child-event', $event)">
|
||||
<Child @click="$emit('child-event')" />
|
||||
</Parent>
|
||||
</GrandParent>
|
||||
```
|
||||
|
||||
## Vue 3 Native Event Behavior
|
||||
|
||||
```javascript
|
||||
// In Vue 3, if you declare an event in emits:
|
||||
defineEmits(['click'])
|
||||
|
||||
// Then @click on the component ONLY listens to emitted events
|
||||
// NOT native click events
|
||||
|
||||
// If you don't declare 'click' in emits:
|
||||
defineEmits(['custom-event'])
|
||||
|
||||
// Then @click on single-root component will:
|
||||
// 1. Fall through to root element as native listener
|
||||
// 2. Fire on native click
|
||||
```
|
||||
|
||||
## Composition API Emit Pattern
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// Define what events this component emits
|
||||
const emit = defineEmits(['click', 'update', 'delete'])
|
||||
|
||||
function handleClick(event) {
|
||||
// Do component logic
|
||||
processClick()
|
||||
|
||||
// Then emit to parent
|
||||
emit('click', event)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleClick">
|
||||
<slot></slot>
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Migration from Vue 2
|
||||
|
||||
```html
|
||||
<!-- Vue 2: Used .native for native events on components -->
|
||||
<MyComponent @click.native="handleClick" />
|
||||
|
||||
<!-- Vue 3: Remove .native, ensure component handles the event -->
|
||||
<MyComponent @click="handleClick" />
|
||||
|
||||
<!-- Make sure MyComponent either:
|
||||
1. Has single root that receives fallthrough attrs
|
||||
2. Explicitly emits 'click' event
|
||||
3. Uses v-bind="$attrs" on intended element -->
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component Events](https://vuejs.org/guide/components/events.html)
|
||||
- [Vue.js Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
|
||||
- [Vue 3 Migration - .native Modifier Removed](https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html)
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
title: Avoid Component Naming Conflicts Between Global and Local
|
||||
impact: HIGH
|
||||
impactDescription: Naming conflicts cause unexpected component rendering and hard-to-debug issues
|
||||
type: gotcha
|
||||
tags: [vue3, component-registration, naming-conflicts, global-local, debugging]
|
||||
---
|
||||
|
||||
# Avoid Component Naming Conflicts Between Global and Local
|
||||
|
||||
**Impact: HIGH** - When a global component and a local component have the same name (or resolve to the same name due to casing differences), unexpected behavior occurs. The precedence rules can be confusing, and the wrong component may render silently without any error. This is particularly problematic when using third-party component libraries.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use unique, prefixed names for global components (e.g., `BaseButton`, `AppHeader`)
|
||||
- [ ] Check for naming conflicts when adding global components
|
||||
- [ ] Explicitly alias local components if there's potential conflict
|
||||
- [ ] When overriding third-party components, document and test thoroughly
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// main.js
|
||||
import { createApp } from 'vue'
|
||||
import Button from './components/Button.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
app.component('Button', Button) // Global Button
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- SomeComponent.vue -->
|
||||
<script setup>
|
||||
// This local Button might conflict with global Button
|
||||
import Button from './local/Button.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Which Button renders? Behavior may be unexpected -->
|
||||
<Button>Click me</Button>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Another confusing scenario -->
|
||||
<script setup>
|
||||
// Registering with camelCase
|
||||
import MyButton from './MyButton.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Using kebab-case - might match a global 'my-button' instead -->
|
||||
<my-button>Click</my-button>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// main.js - use prefixes for global components
|
||||
import { createApp } from 'vue'
|
||||
import BaseButton from './components/BaseButton.vue'
|
||||
import BaseIcon from './components/BaseIcon.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
app.component('BaseButton', BaseButton)
|
||||
app.component('BaseIcon', BaseIcon)
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- SomeComponent.vue -->
|
||||
<script setup>
|
||||
// Local components have distinct names
|
||||
import SubmitButton from './local/SubmitButton.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- No ambiguity - each name is unique -->
|
||||
<BaseButton>Generic button</BaseButton>
|
||||
<SubmitButton>Submit form</SubmitButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Explicit Aliasing for Clarity
|
||||
|
||||
When you intentionally want to override or have similar names, use explicit aliasing:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// Explicit alias to avoid confusion
|
||||
import { default as LocalButton } from './Button.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<LocalButton>Local version</LocalButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Options API with explicit component name -->
|
||||
<script>
|
||||
import ThirdPartyModal from 'some-library'
|
||||
import CustomModal from './CustomModal.vue'
|
||||
|
||||
export default {
|
||||
components: {
|
||||
// Explicit names prevent ambiguity
|
||||
LibraryModal: ThirdPartyModal,
|
||||
CustomModal
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Resolution Order
|
||||
|
||||
Understanding Vue's component resolution order helps debug issues:
|
||||
|
||||
1. **Local registration** takes precedence over global
|
||||
2. **Exact case match** takes precedence over case-insensitive match
|
||||
3. Self-referencing component name (file name) has lowest priority
|
||||
|
||||
```vue
|
||||
<!-- If all exist: GlobalButton, local Button, and file is Button.vue -->
|
||||
<script setup>
|
||||
import Button from './Button.vue' // Local registration
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Resolves to locally imported Button, not global -->
|
||||
<Button />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Third-Party Library Conflicts
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// Be explicit when using components from multiple libraries
|
||||
import { Button as AntButton } from 'ant-design-vue'
|
||||
import { Button as ElButton } from 'element-plus'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AntButton>Ant Design</AntButton>
|
||||
<ElButton>Element Plus</ElButton>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Naming Convention Strategy
|
||||
|
||||
| Component Type | Naming Pattern | Example |
|
||||
|----------------|---------------|---------|
|
||||
| Base/Global | `Base*` or `App*` prefix | `BaseButton`, `AppHeader` |
|
||||
| Domain-specific | Domain prefix | `UserCard`, `ProductList` |
|
||||
| Page components | `*Page` or `*View` suffix | `HomePage`, `UserView` |
|
||||
| Layout components | `*Layout` suffix | `DefaultLayout`, `AdminLayout` |
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html)
|
||||
- [GitHub Issue: Global component naming conflicts](https://github.com/vuejs/vue/issues/4434)
|
||||
@@ -0,0 +1,176 @@
|
||||
---
|
||||
title: Component Refs Require defineExpose with Script Setup
|
||||
impact: HIGH
|
||||
impactDescription: Parent components cannot access child ref properties unless explicitly exposed
|
||||
type: gotcha
|
||||
tags: [vue3, template-refs, script-setup, defineExpose, component-communication]
|
||||
---
|
||||
|
||||
# Component Refs Require defineExpose with Script Setup
|
||||
|
||||
**Impact: HIGH** - Components using `<script setup>` are private by default. A parent component using a template ref to access a child will get an empty object unless the child explicitly exposes properties using `defineExpose()`. This is a fundamental change from Options API behavior.
|
||||
|
||||
This catches many developers off-guard when migrating from Options API, where `this.$refs.child` gave full access to the child instance.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use `defineExpose()` to explicitly expose properties/methods to parent refs
|
||||
- [ ] Only expose what's necessary - keep component internals private
|
||||
- [ ] Document exposed APIs as they form your component's public interface
|
||||
- [ ] Prefer props/emit for parent-child communication; use refs sparingly
|
||||
- [ ] Call defineExpose before any await operation (see async caveat)
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
const internalState = ref('private')
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
function reset() {
|
||||
count.value = 0
|
||||
}
|
||||
|
||||
// WRONG: Nothing exposed - parent ref sees empty object
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>{{ count }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
|
||||
const childRef = ref(null)
|
||||
|
||||
onMounted(() => {
|
||||
// WRONG: childRef.value is {} - empty object!
|
||||
console.log(childRef.value.count) // undefined
|
||||
childRef.value.increment() // TypeError: not a function
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChildComponent ref="childRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
const internalState = ref('private') // Keep this private
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
function reset() {
|
||||
count.value = 0
|
||||
}
|
||||
|
||||
// CORRECT: Explicitly expose public API
|
||||
defineExpose({
|
||||
count, // Expose the ref
|
||||
increment, // Expose methods
|
||||
reset
|
||||
// internalState NOT exposed - stays private
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>{{ count }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
|
||||
const childRef = ref(null)
|
||||
|
||||
onMounted(() => {
|
||||
// CORRECT: Can access exposed properties
|
||||
console.log(childRef.value.count) // 0
|
||||
childRef.value.increment() // Works!
|
||||
|
||||
// internalState is not accessible (private)
|
||||
console.log(childRef.value.internalState) // undefined
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChildComponent ref="childRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Input wrapper example - exposing native element -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const inputEl = ref(null)
|
||||
|
||||
// Expose the native input for parent to access (e.g., for focus)
|
||||
defineExpose({
|
||||
focus: () => inputEl.value?.focus(),
|
||||
blur: () => inputEl.value?.blur(),
|
||||
// Or expose the element directly
|
||||
el: inputEl
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="inputEl" v-bind="$attrs" />
|
||||
</template>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Options API equivalent using expose option
|
||||
export default {
|
||||
expose: ['count', 'increment', 'reset'],
|
||||
data() {
|
||||
return {
|
||||
count: 0,
|
||||
internalState: 'private'
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
increment() { this.count++ },
|
||||
reset() { this.count = 0 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practice Reminder
|
||||
|
||||
Component refs create tight coupling between parent and child. Prefer standard patterns:
|
||||
|
||||
```vue
|
||||
<!-- PREFERRED: Use props and emit for communication -->
|
||||
<script setup>
|
||||
const props = defineProps(['modelValue'])
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
</script>
|
||||
|
||||
<!-- Only use refs for imperative actions like focus(), scrollTo(), etc. -->
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component Refs](https://vuejs.org/guide/essentials/template-refs.html#ref-on-component)
|
||||
- [Script Setup - defineExpose](https://vuejs.org/api/sfc-script-setup.html#defineexpose)
|
||||
@@ -0,0 +1,208 @@
|
||||
---
|
||||
title: Avoid Hidden Side Effects in Composables
|
||||
impact: HIGH
|
||||
impactDescription: Side effects hidden in composables make debugging difficult and create implicit coupling between components
|
||||
type: best-practice
|
||||
tags: [vue3, composables, composition-api, side-effects, provide-inject, global-state]
|
||||
---
|
||||
|
||||
# Avoid Hidden Side Effects in Composables
|
||||
|
||||
**Impact: HIGH** - Composables should encapsulate stateful logic, not hide side effects that affect things outside their scope. Hidden side effects like modifying global state, using provide/inject internally, or manipulating the DOM directly make composables unpredictable and hard to debug.
|
||||
|
||||
When a composable has unexpected side effects, consumers can't reason about what calling it will do. This leads to bugs that are difficult to trace and composables that can't be safely reused.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Avoid using provide/inject inside composables (make dependencies explicit)
|
||||
- [ ] Don't modify Pinia/Vuex store state internally (accept store as parameter instead)
|
||||
- [ ] Don't manipulate DOM directly (use template refs passed as arguments)
|
||||
- [ ] Document any unavoidable side effects clearly
|
||||
- [ ] Keep composables focused on returning reactive state and methods
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// WRONG: Hidden provide/inject dependency
|
||||
export function useTheme() {
|
||||
// Consumer has no idea this depends on a provided theme
|
||||
const theme = inject('theme') // What if nothing provides this?
|
||||
|
||||
const isDark = computed(() => theme?.mode === 'dark')
|
||||
return { isDark }
|
||||
}
|
||||
|
||||
// WRONG: Modifying global store internally
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
export function useLogin() {
|
||||
const userStore = useUserStore()
|
||||
|
||||
async function login(credentials) {
|
||||
const user = await api.login(credentials)
|
||||
// Hidden side effect: modifying global state
|
||||
userStore.setUser(user)
|
||||
userStore.setToken(user.token)
|
||||
// Consumer doesn't know the store was modified!
|
||||
}
|
||||
|
||||
return { login }
|
||||
}
|
||||
|
||||
// WRONG: Hidden DOM manipulation
|
||||
export function useFocusTrap() {
|
||||
onMounted(() => {
|
||||
// Which element? Consumer has no control
|
||||
document.querySelector('.modal')?.focus()
|
||||
})
|
||||
}
|
||||
|
||||
// WRONG: Hidden provide that affects descendants
|
||||
export function useFormContext() {
|
||||
const form = reactive({ values: {}, errors: {} })
|
||||
// Components calling this have no idea it provides something
|
||||
provide('form-context', form)
|
||||
return form
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// CORRECT: Explicit dependency injection
|
||||
export function useTheme(injectedTheme) {
|
||||
// If no theme passed, consumer must handle it
|
||||
const theme = injectedTheme ?? { mode: 'light' }
|
||||
|
||||
const isDark = computed(() => theme.mode === 'dark')
|
||||
return { isDark }
|
||||
}
|
||||
|
||||
// Usage - dependency is explicit
|
||||
const theme = inject('theme', { mode: 'light' })
|
||||
const { isDark } = useTheme(theme)
|
||||
|
||||
// CORRECT: Return actions, let consumer decide when to call them
|
||||
export function useLogin() {
|
||||
const user = ref(null)
|
||||
const token = ref(null)
|
||||
const isLoading = ref(false)
|
||||
const error = ref(null)
|
||||
|
||||
async function login(credentials) {
|
||||
isLoading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await api.login(credentials)
|
||||
user.value = response.user
|
||||
token.value = response.token
|
||||
return response
|
||||
} catch (e) {
|
||||
error.value = e
|
||||
throw e
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return { user, token, isLoading, error, login }
|
||||
}
|
||||
|
||||
// Consumer decides what to do with the result
|
||||
const { user, token, login } = useLogin()
|
||||
const userStore = useUserStore()
|
||||
|
||||
async function handleLogin(credentials) {
|
||||
await login(credentials)
|
||||
// Consumer explicitly updates the store
|
||||
userStore.setUser(user.value)
|
||||
userStore.setToken(token.value)
|
||||
}
|
||||
|
||||
// CORRECT: Accept element as parameter
|
||||
export function useFocusTrap(targetRef) {
|
||||
onMounted(() => {
|
||||
targetRef.value?.focus()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
// Cleanup focus trap
|
||||
})
|
||||
}
|
||||
|
||||
// Usage - consumer controls which element
|
||||
const modalRef = ref(null)
|
||||
useFocusTrap(modalRef)
|
||||
|
||||
// CORRECT: Separate composable from provider
|
||||
export function useFormContext() {
|
||||
const form = reactive({ values: {}, errors: {} })
|
||||
return form
|
||||
}
|
||||
|
||||
// In parent component - explicit provide
|
||||
const form = useFormContext()
|
||||
provide('form-context', form)
|
||||
```
|
||||
|
||||
## Acceptable Side Effects (With Documentation)
|
||||
|
||||
Some side effects are acceptable when they're the core purpose of the composable:
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Tracks mouse position globally.
|
||||
*
|
||||
* SIDE EFFECTS:
|
||||
* - Adds 'mousemove' event listener to window (cleaned up on unmount)
|
||||
*
|
||||
* @returns {Object} Mouse coordinates { x, y }
|
||||
*/
|
||||
export function useMouse() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
// This side effect is the whole point of the composable
|
||||
// and is properly cleaned up
|
||||
onMounted(() => window.addEventListener('mousemove', update))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', update))
|
||||
|
||||
function update(event) {
|
||||
x.value = event.pageX
|
||||
y.value = event.pageY
|
||||
}
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
```
|
||||
|
||||
## Pattern: Dependency Injection for Flexibility
|
||||
|
||||
```javascript
|
||||
// Composable accepts its dependencies
|
||||
export function useDataFetcher(apiClient, cache = null) {
|
||||
const data = ref(null)
|
||||
|
||||
async function fetch(url) {
|
||||
if (cache) {
|
||||
const cached = cache.get(url)
|
||||
if (cached) {
|
||||
data.value = cached
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
data.value = await apiClient.get(url)
|
||||
cache?.set(url, data.value)
|
||||
}
|
||||
|
||||
return { data, fetch }
|
||||
}
|
||||
|
||||
// Usage - dependencies are explicit and testable
|
||||
const apiClient = inject('apiClient')
|
||||
const cache = inject('cache', null)
|
||||
const { data, fetch } = useDataFetcher(apiClient, cache)
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Composables](https://vuejs.org/guide/reusability/composables.html)
|
||||
- [Common Mistakes Creating Composition Functions](https://www.telerik.com/blogs/common-mistakes-creating-composition-functions-vue)
|
||||
@@ -0,0 +1,141 @@
|
||||
---
|
||||
title: Call Composables Only in Setup Context Synchronously
|
||||
impact: HIGH
|
||||
impactDescription: Composables called outside setup context or asynchronously fail to register lifecycle hooks and may cause memory leaks
|
||||
type: gotcha
|
||||
tags: [vue3, composables, composition-api, setup, async, lifecycle]
|
||||
---
|
||||
|
||||
# Call Composables Only in Setup Context Synchronously
|
||||
|
||||
**Impact: HIGH** - Composables must be called synchronously within `<script setup>`, the `setup()` function, or lifecycle hooks. Calling composables asynchronously (after await), in callbacks, or outside component context prevents Vue from associating lifecycle hooks with the component instance, causing silent failures.
|
||||
|
||||
This is critical because composables often register `onMounted` and `onUnmounted` hooks internally. If called in the wrong context, these hooks are never registered, leading to uninitialized state or memory leaks.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Call all composables at the top level of `<script setup>` or `setup()`
|
||||
- [ ] Never call composables inside async callbacks, setTimeout, or Promise.then
|
||||
- [ ] Never call composables conditionally (if/else) - call unconditionally and handle the condition inside
|
||||
- [ ] Never call composables inside loops - restructure to call once with array data
|
||||
- [ ] Exception: Composables CAN be called in lifecycle hooks like `onMounted`
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { useFetch } from './composables/useFetch'
|
||||
import { useAuth } from './composables/useAuth'
|
||||
|
||||
// WRONG: Composable called after await
|
||||
const config = await loadConfig()
|
||||
const { data } = useFetch(config.apiUrl) // Lifecycle hooks won't register!
|
||||
|
||||
// WRONG: Composable called conditionally
|
||||
if (someCondition) {
|
||||
const { user } = useAuth() // Inconsistent hook registration!
|
||||
}
|
||||
|
||||
// WRONG: Composable called in callback
|
||||
setTimeout(() => {
|
||||
const { data } = useFetch('/api/delayed') // No component context!
|
||||
}, 1000)
|
||||
|
||||
// WRONG: Composable called in loop
|
||||
for (const url of urls) {
|
||||
const { data } = useFetch(url) // Creates multiple instances incorrectly
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useFetch } from './composables/useFetch'
|
||||
import { useAuth } from './composables/useAuth'
|
||||
|
||||
// CORRECT: Call composables synchronously at top level
|
||||
const { user, isAuthenticated } = useAuth()
|
||||
const apiUrl = ref('/api/default')
|
||||
const { data, execute } = useFetch(apiUrl)
|
||||
|
||||
// Handle async config loading differently
|
||||
onMounted(async () => {
|
||||
const config = await loadConfig()
|
||||
apiUrl.value = config.apiUrl // Update the ref, composable reacts
|
||||
})
|
||||
|
||||
// CORRECT: Handle condition inside, not outside
|
||||
const showUserData = computed(() => isAuthenticated.value && someCondition)
|
||||
|
||||
// CORRECT: For multiple URLs, use a different pattern
|
||||
const urls = ref(['/api/a', '/api/b', '/api/c'])
|
||||
const results = ref([])
|
||||
|
||||
// Either fetch in onMounted or use a composable designed for arrays
|
||||
onMounted(async () => {
|
||||
results.value = await Promise.all(urls.value.map(url => fetch(url)))
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Exception: Calling in Lifecycle Hooks
|
||||
|
||||
Composables CAN be called inside lifecycle hooks because Vue maintains the component context:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { onMounted } from 'vue'
|
||||
import { useEventListener } from '@vueuse/core'
|
||||
|
||||
// CORRECT: Called in lifecycle hook - component context is available
|
||||
onMounted(() => {
|
||||
// This works because we're still in the component's execution context
|
||||
useEventListener(document, 'visibilitychange', handleVisibility)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Special Case: Async Setup in `<script setup>`
|
||||
|
||||
Top-level await in `<script setup>` is special - Vue's compiler automatically preserves context:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useFetch } from './composables/useFetch'
|
||||
|
||||
// CORRECT: Top-level await in <script setup> preserves context
|
||||
// Vue compiler handles this specially
|
||||
const config = await loadConfig()
|
||||
const { data } = useFetch(config.apiUrl) // This works!
|
||||
|
||||
// But nested awaits still break context:
|
||||
async function initLater() {
|
||||
await delay(1000)
|
||||
const { data } = useFetch('/api/late') // WRONG: This won't work!
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Why This Matters
|
||||
|
||||
When you call a composable, Vue needs to know which component instance to associate it with. This association happens through an internal "current instance" that's only set during synchronous setup execution.
|
||||
|
||||
```javascript
|
||||
// Inside a composable
|
||||
export function useFetch(url) {
|
||||
const data = ref(null)
|
||||
|
||||
// These need the current component instance!
|
||||
onMounted(() => { /* ... */ })
|
||||
onUnmounted(() => { /* cleanup */ })
|
||||
|
||||
// If called outside setup context, Vue can't find the instance
|
||||
// and these hooks are silently ignored
|
||||
return { data }
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Composables - Usage Restrictions](https://vuejs.org/guide/reusability/composables.html#usage-restrictions)
|
||||
- [Vue.js Composition API - Setup Context](https://vuejs.org/api/composition-api-setup.html)
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: Follow Composable Naming Convention and Return Pattern
|
||||
impact: MEDIUM
|
||||
impactDescription: Inconsistent composable patterns lead to confusing APIs and reactivity issues when destructuring
|
||||
type: best-practice
|
||||
tags: [vue3, composables, composition-api, naming, conventions, refs]
|
||||
---
|
||||
|
||||
# Follow Composable Naming Convention and Return Pattern
|
||||
|
||||
**Impact: MEDIUM** - Vue composables should follow established conventions: prefix names with "use" and return plain objects containing refs (not reactive objects). Returning reactive objects causes reactivity loss when destructuring, while inconsistent naming makes code harder to understand.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Name composables with "use" prefix (e.g., `useMouse`, `useFetch`, `useAuth`)
|
||||
- [ ] Return a plain object containing refs, not a reactive object
|
||||
- [ ] Allow both destructuring and object-style access
|
||||
- [ ] Document the returned refs for consumers
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// WRONG: No "use" prefix - unclear it's a composable
|
||||
export function mousePosition() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
return { x, y }
|
||||
}
|
||||
|
||||
// WRONG: Returning reactive object - destructuring loses reactivity
|
||||
export function useMouse() {
|
||||
const state = reactive({
|
||||
x: 0,
|
||||
y: 0
|
||||
})
|
||||
// When consumer destructures: const { x, y } = useMouse()
|
||||
// x and y become plain values, not reactive!
|
||||
return state
|
||||
}
|
||||
|
||||
// WRONG: Returning single ref directly - inconsistent API
|
||||
export function useCounter() {
|
||||
const count = ref(0)
|
||||
return count // Consumer must use .value everywhere
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// CORRECT: "use" prefix and returns plain object with refs
|
||||
export function useMouse() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
function update(event) {
|
||||
x.value = event.pageX
|
||||
y.value = event.pageY
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('mousemove', update))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', update))
|
||||
|
||||
// Return plain object containing refs
|
||||
return { x, y }
|
||||
}
|
||||
|
||||
// Consumer can destructure and keep reactivity
|
||||
const { x, y } = useMouse()
|
||||
watch(x, (newX) => console.log('x changed:', newX)) // Works!
|
||||
|
||||
// Or use as object if preferred
|
||||
const mouse = useMouse()
|
||||
console.log(mouse.x.value)
|
||||
```
|
||||
|
||||
## Using reactive() Wrapper for Auto-Unwrapping
|
||||
|
||||
If consumers prefer auto-unwrapping (no `.value`), they can wrap the result:
|
||||
|
||||
```javascript
|
||||
import { reactive } from 'vue'
|
||||
import { useMouse } from './composables/useMouse'
|
||||
|
||||
// Wrapping in reactive() links the refs
|
||||
const mouse = reactive(useMouse())
|
||||
|
||||
// Now access without .value
|
||||
console.log(mouse.x) // Auto-unwrapped, still reactive
|
||||
|
||||
// But DON'T destructure from this!
|
||||
const { x } = reactive(useMouse()) // WRONG: loses reactivity again
|
||||
```
|
||||
|
||||
## Pattern: Returning Both State and Actions
|
||||
|
||||
```javascript
|
||||
// Composable with state AND methods
|
||||
export function useCounter(initialValue = 0) {
|
||||
const count = ref(initialValue)
|
||||
const doubleCount = computed(() => count.value * 2)
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
function decrement() {
|
||||
count.value--
|
||||
}
|
||||
|
||||
function reset() {
|
||||
count.value = initialValue
|
||||
}
|
||||
|
||||
// Return all refs and functions in plain object
|
||||
return {
|
||||
count,
|
||||
doubleCount,
|
||||
increment,
|
||||
decrement,
|
||||
reset
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const { count, doubleCount, increment, reset } = useCounter(10)
|
||||
```
|
||||
|
||||
## Naming Convention Examples
|
||||
|
||||
| Good Name | Bad Name | Reason |
|
||||
|-----------|----------|--------|
|
||||
| `useFetch` | `fetch` | Conflicts with native fetch |
|
||||
| `useAuth` | `authStore` | "Store" implies Pinia/Vuex |
|
||||
| `useLocalStorage` | `localStorage` | Conflicts with native API |
|
||||
| `useFormValidation` | `validateForm` | Sounds like a one-shot function |
|
||||
| `useWindowSize` | `getWindowSize` | "get" implies synchronous getter |
|
||||
|
||||
## Reference
|
||||
- [Vue.js Composables - Conventions and Best Practices](https://vuejs.org/guide/reusability/composables.html#conventions-and-best-practices)
|
||||
- [Vue.js Composables - Return Values](https://vuejs.org/guide/reusability/composables.html#return-values)
|
||||
@@ -0,0 +1,182 @@
|
||||
---
|
||||
title: Call toValue() Inside watchEffect for Proper Dependency Tracking
|
||||
impact: HIGH
|
||||
impactDescription: Calling toValue() outside watchEffect prevents reactive dependency tracking, causing the effect to never re-run
|
||||
type: gotcha
|
||||
tags: [vue3, composables, composition-api, watchEffect, toValue, reactivity]
|
||||
---
|
||||
|
||||
# Call toValue() Inside watchEffect for Proper Dependency Tracking
|
||||
|
||||
**Impact: HIGH** - When writing composables that accept `MaybeRefOrGetter` arguments, you must call `toValue()` inside the `watchEffect` callback, not outside. If you extract the value before the watchEffect, Vue cannot track the dependency and the effect will never re-run when the source changes.
|
||||
|
||||
This is a subtle but critical mistake that leads to composables that work with initial values but never update.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Always call `toValue()` inside `watchEffect` callbacks, not before
|
||||
- [ ] Similarly, access `.value` on refs inside watchEffect, not outside
|
||||
- [ ] For `watch()`, use a getter function that calls `toValue()`
|
||||
- [ ] Test that composables update when their inputs change
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
import { ref, watchEffect, toValue } from 'vue'
|
||||
|
||||
export function useFetch(url) {
|
||||
const data = ref(null)
|
||||
const error = ref(null)
|
||||
|
||||
// WRONG: toValue called outside watchEffect
|
||||
// This extracts the value ONCE and passes a static string
|
||||
const urlValue = toValue(url)
|
||||
|
||||
watchEffect(async () => {
|
||||
try {
|
||||
// urlValue is a static string - no dependency tracked!
|
||||
const response = await fetch(urlValue)
|
||||
data.value = await response.json()
|
||||
} catch (e) {
|
||||
error.value = e
|
||||
}
|
||||
})
|
||||
|
||||
return { data, error }
|
||||
}
|
||||
|
||||
// When used like this:
|
||||
const apiUrl = ref('/api/users')
|
||||
const { data } = useFetch(apiUrl)
|
||||
|
||||
// Later...
|
||||
apiUrl.value = '/api/products' // useFetch will NOT refetch!
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
import { ref, watchEffect, toValue } from 'vue'
|
||||
|
||||
export function useFetch(url) {
|
||||
const data = ref(null)
|
||||
const error = ref(null)
|
||||
|
||||
watchEffect(async () => {
|
||||
// CORRECT: toValue called INSIDE watchEffect
|
||||
// Vue tracks this as a dependency
|
||||
const urlValue = toValue(url)
|
||||
|
||||
try {
|
||||
const response = await fetch(urlValue)
|
||||
data.value = await response.json()
|
||||
} catch (e) {
|
||||
error.value = e
|
||||
}
|
||||
})
|
||||
|
||||
return { data, error }
|
||||
}
|
||||
|
||||
// Now when used:
|
||||
const apiUrl = ref('/api/users')
|
||||
const { data } = useFetch(apiUrl)
|
||||
|
||||
// Later...
|
||||
apiUrl.value = '/api/products' // useFetch WILL refetch!
|
||||
```
|
||||
|
||||
## The Same Applies to Direct Ref Access
|
||||
|
||||
```javascript
|
||||
// WRONG: Accessing .value outside the effect
|
||||
export function useDebounce(source, delay = 300) {
|
||||
// This captures the initial value, not a reactive dependency
|
||||
const initialValue = source.value // or toValue(source)
|
||||
|
||||
watchEffect(() => {
|
||||
// initialValue is static - this only runs once
|
||||
console.log('Value:', initialValue)
|
||||
})
|
||||
}
|
||||
|
||||
// CORRECT: Access inside the effect
|
||||
export function useDebounce(source, delay = 300) {
|
||||
watchEffect(() => {
|
||||
// Vue tracks source.value or toValue(source) as dependency
|
||||
console.log('Value:', toValue(source))
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Pattern: Using watch() with Getter Functions
|
||||
|
||||
For `watch()`, wrap `toValue()` in a getter:
|
||||
|
||||
```javascript
|
||||
import { ref, watch, toValue } from 'vue'
|
||||
|
||||
export function useLocalStorage(key, defaultValue) {
|
||||
const data = ref(defaultValue)
|
||||
|
||||
// CORRECT: Use getter function with watch
|
||||
watch(
|
||||
() => toValue(key), // Getter calls toValue, tracks dependency
|
||||
(newKey) => {
|
||||
const stored = localStorage.getItem(newKey)
|
||||
data.value = stored ? JSON.parse(stored) : defaultValue
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
return data
|
||||
}
|
||||
```
|
||||
|
||||
## Why This Happens
|
||||
|
||||
Vue's reactivity tracking works by detecting property accesses during effect execution:
|
||||
|
||||
```javascript
|
||||
watchEffect(() => {
|
||||
// When this runs, Vue is "recording" what reactive sources are accessed
|
||||
const value = someRef.value // Vue records: "this effect depends on someRef"
|
||||
})
|
||||
|
||||
// But if you extract the value before:
|
||||
const value = someRef.value // Vue isn't recording yet
|
||||
watchEffect(() => {
|
||||
console.log(value) // Just using a plain JavaScript variable
|
||||
})
|
||||
```
|
||||
|
||||
`toValue()` works the same way - it accesses `.value` internally, so it must happen during effect execution for tracking to work.
|
||||
|
||||
## Quick Checklist for Composable Authors
|
||||
|
||||
When accepting `MaybeRefOrGetter` inputs:
|
||||
|
||||
1. Store the raw argument (don't call `toValue` during setup)
|
||||
2. Call `toValue()` inside any reactive context (`watchEffect`, `watch`, `computed`)
|
||||
3. Test with both static values AND refs that change
|
||||
|
||||
```javascript
|
||||
export function useMyComposable(input) {
|
||||
// Store raw - don't extract value here
|
||||
// const value = toValue(input) // WRONG
|
||||
|
||||
const result = computed(() => {
|
||||
// Extract value inside reactive context
|
||||
return transform(toValue(input)) // CORRECT
|
||||
})
|
||||
|
||||
watchEffect(() => {
|
||||
// Extract value inside reactive context
|
||||
doSomething(toValue(input)) // CORRECT
|
||||
})
|
||||
|
||||
return { result }
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Reactivity API - toValue](https://vuejs.org/api/reactivity-utilities.html#tovalue)
|
||||
- [Vue.js Composables - Accepting Ref Arguments](https://vuejs.org/guide/reusability/composables.html#accepting-reactive-state)
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: Composition API Uses Mutable Reactivity, Not Functional Programming
|
||||
impact: MEDIUM
|
||||
impactDescription: Misunderstanding the paradigm leads to incorrect state management patterns
|
||||
type: gotcha
|
||||
tags: [vue3, composition-api, reactivity, functional-programming, paradigm]
|
||||
---
|
||||
|
||||
# Composition API Uses Mutable Reactivity, Not Functional Programming
|
||||
|
||||
**Impact: MEDIUM** - Despite being function-based, the Composition API follows Vue's mutable, fine-grained reactivity paradigm—NOT functional programming principles. Treating it like a functional paradigm leads to incorrect patterns like unnecessary cloning, immutable-style updates, or avoiding mutation when mutation is the intended pattern.
|
||||
|
||||
Vue's Composition API leverages imported functions to organize code, but the underlying model is based on mutable reactive state that Vue tracks and responds to. This is fundamentally different from functional programming with immutability (like Redux reducers).
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Mutate reactive state directly - don't create new objects for every update
|
||||
- [ ] Don't apply immutability patterns unnecessarily (spreading, Object.assign for updates)
|
||||
- [ ] Understand that `ref()` and `reactive()` enable mutable state tracking
|
||||
- [ ] Use Vue's reactivity as intended: direct mutation with automatic tracking
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
import { ref } from 'vue'
|
||||
|
||||
const todos = ref([])
|
||||
|
||||
// WRONG: Treating Vue like Redux/functional - unnecessary immutability
|
||||
function addTodo(todo) {
|
||||
// Creating a new array every time is wasteful in Vue
|
||||
todos.value = [...todos.value, todo]
|
||||
}
|
||||
|
||||
function updateTodo(id, updates) {
|
||||
// Unnecessary spread - Vue tracks mutations directly
|
||||
todos.value = todos.value.map(t =>
|
||||
t.id === id ? { ...t, ...updates } : t
|
||||
)
|
||||
}
|
||||
|
||||
const user = ref({ name: 'John', age: 30 })
|
||||
|
||||
// WRONG: Creating new object for simple update
|
||||
function updateName(newName) {
|
||||
user.value = { ...user.value, name: newName }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
const todos = ref([])
|
||||
|
||||
// CORRECT: Mutate directly - Vue tracks the change
|
||||
function addTodo(todo) {
|
||||
todos.value.push(todo) // Direct mutation is the Vue way
|
||||
}
|
||||
|
||||
function updateTodo(id, updates) {
|
||||
const todo = todos.value.find(t => t.id === id)
|
||||
if (todo) {
|
||||
Object.assign(todo, updates) // Direct mutation
|
||||
}
|
||||
}
|
||||
|
||||
const user = ref({ name: 'John', age: 30 })
|
||||
|
||||
// CORRECT: Mutate the property directly
|
||||
function updateName(newName) {
|
||||
user.value.name = newName // Vue tracks this!
|
||||
}
|
||||
|
||||
// Or with reactive():
|
||||
const state = reactive({ name: 'John', age: 30 })
|
||||
|
||||
function updateNameReactive(newName) {
|
||||
state.name = newName // Direct mutation, reactivity preserved
|
||||
}
|
||||
```
|
||||
|
||||
## When Immutability Patterns Make Sense
|
||||
|
||||
```javascript
|
||||
// Immutability IS appropriate when:
|
||||
|
||||
// 1. Replacing the entire state (e.g., from API response)
|
||||
const users = ref([])
|
||||
async function fetchUsers() {
|
||||
users.value = await api.getUsers() // Complete replacement is fine
|
||||
}
|
||||
|
||||
// 2. When you need a snapshot for comparison
|
||||
const previousState = { ...currentState } // For undo/redo
|
||||
|
||||
// 3. When passing data to external libraries expecting immutable data
|
||||
const chartData = computed(() => [...rawData.value]) // Copy for chart lib
|
||||
```
|
||||
|
||||
## The Vue Mental Model
|
||||
|
||||
```javascript
|
||||
// Vue's reactivity is like a spreadsheet:
|
||||
// - Cell A1 contains a value (ref)
|
||||
// - Cell B1 has a formula referencing A1 (computed)
|
||||
// - Change A1, and B1 automatically updates
|
||||
|
||||
const a1 = ref(10)
|
||||
const b1 = computed(() => a1.value * 2)
|
||||
|
||||
// You CHANGE A1 (mutate), you don't create a new A1
|
||||
a1.value = 20 // b1 automatically becomes 40
|
||||
|
||||
// This is fundamentally different from:
|
||||
// state = reducer(state, action) // Functional/Redux pattern
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Composition API FAQ](https://vuejs.org/guide/extras/composition-api-faq.html)
|
||||
- [Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
title: Top-Level await in script setup Preserves Component Context
|
||||
impact: HIGH
|
||||
impactDescription: Misunderstanding async context causes lifecycle hooks and watchers to silently fail
|
||||
type: gotcha
|
||||
tags: [vue3, composition-api, script-setup, async, await, suspense]
|
||||
---
|
||||
|
||||
# Top-Level await in script setup Preserves Component Context
|
||||
|
||||
**Impact: HIGH** - In `<script setup>`, top-level `await` statements preserve component context (allowing lifecycle hooks and watchers after `await`), but this is a special case. Nested async functions or callbacks lose context, causing lifecycle hooks to silently fail.
|
||||
|
||||
Vue's compiler automatically injects context restoration after each top-level await in `<script setup>`. This doesn't apply to `setup()` function or nested async contexts.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Understand that top-level await in `<script setup>` is specially handled
|
||||
- [ ] Never register lifecycle hooks in nested async functions
|
||||
- [ ] Use `<Suspense>` when using async `<script setup>` components
|
||||
- [ ] In regular `setup()`, never use await before lifecycle hook registration
|
||||
- [ ] Register hooks synchronously, then do async work inside them
|
||||
|
||||
**Top-Level await Works (script setup only):**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
|
||||
// This is TOP-LEVEL await - Vue compiler preserves context
|
||||
const config = await fetchConfig() // OK!
|
||||
|
||||
// These hooks work because Vue restored context
|
||||
onMounted(() => {
|
||||
console.log('This will run!') // Works
|
||||
})
|
||||
|
||||
watch(someRef, () => {
|
||||
console.log('This will track!') // Works
|
||||
})
|
||||
|
||||
// Another top-level await - still OK
|
||||
const data = await fetchData(config.apiUrl) // OK!
|
||||
|
||||
// Still works after multiple awaits
|
||||
onMounted(() => {
|
||||
console.log('This also runs!') // Works
|
||||
})
|
||||
</script>
|
||||
|
||||
<!-- IMPORTANT: Parent must use Suspense -->
|
||||
<template>
|
||||
<Suspense>
|
||||
<AsyncComponent />
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Nested Async Breaks Context:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
|
||||
// WRONG: Nested async function - context lost after await
|
||||
async function initializeData() {
|
||||
const config = await fetchConfig()
|
||||
|
||||
// BUG: This hook will NOT be registered!
|
||||
// We're no longer in the synchronous setup context
|
||||
onMounted(() => {
|
||||
console.log('This will NEVER run!') // Silent failure
|
||||
})
|
||||
|
||||
// BUG: This watcher won't auto-dispose on unmount
|
||||
watch(someRef, () => {
|
||||
console.log('Memory leak - not cleaned up!')
|
||||
})
|
||||
}
|
||||
|
||||
// Calling the async function
|
||||
initializeData() // Hooks inside won't work!
|
||||
|
||||
// WRONG: Callbacks also lose context
|
||||
setTimeout(async () => {
|
||||
await delay(100)
|
||||
onMounted(() => {
|
||||
console.log('Never runs!') // Silent failure
|
||||
})
|
||||
}, 0)
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct Patterns:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
|
||||
const data = ref(null)
|
||||
const config = ref(null)
|
||||
|
||||
// CORRECT: Register hooks synchronously FIRST
|
||||
onMounted(async () => {
|
||||
// Then do async work INSIDE the hook
|
||||
config.value = await fetchConfig()
|
||||
data.value = await fetchData(config.value.apiUrl)
|
||||
})
|
||||
|
||||
// CORRECT: Watchers registered synchronously
|
||||
watch(config, async (newConfig) => {
|
||||
if (newConfig) {
|
||||
data.value = await fetchData(newConfig.apiUrl)
|
||||
}
|
||||
})
|
||||
|
||||
// Or use top-level await for initial data
|
||||
const initialConfig = await fetchConfig() // OK - top level
|
||||
config.value = initialConfig
|
||||
|
||||
onMounted(() => {
|
||||
console.log('Works!') // Context preserved by compiler
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**setup() Function (Not script setup):**
|
||||
```javascript
|
||||
// In regular setup(), await ALWAYS breaks context
|
||||
export default {
|
||||
async setup() {
|
||||
const data = ref(null)
|
||||
|
||||
// WRONG: Hooks after await won't register
|
||||
const config = await fetchConfig()
|
||||
|
||||
onMounted(() => {
|
||||
console.log('Never runs!') // Silent failure!
|
||||
})
|
||||
|
||||
return { data }
|
||||
}
|
||||
}
|
||||
|
||||
// CORRECT: Register hooks before any await
|
||||
export default {
|
||||
async setup() {
|
||||
const data = ref(null)
|
||||
|
||||
// Register hooks FIRST (synchronous)
|
||||
onMounted(async () => {
|
||||
const config = await fetchConfig()
|
||||
data.value = await fetchData(config)
|
||||
})
|
||||
|
||||
// Now you can await if needed
|
||||
// But hooks must be registered before this point
|
||||
|
||||
return { data }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Why This Happens
|
||||
|
||||
```javascript
|
||||
// Vue tracks the "current component instance" during setup
|
||||
// This is like a global variable that gets set and cleared
|
||||
|
||||
// During synchronous setup:
|
||||
function setup() {
|
||||
currentInstance = this // Vue sets this
|
||||
|
||||
onMounted(cb) // Uses currentInstance to register
|
||||
|
||||
// After await, JavaScript resumes in a microtask
|
||||
await something()
|
||||
|
||||
// currentInstance is now null or different!
|
||||
onMounted(cb) // Can't find the instance - silently fails
|
||||
}
|
||||
|
||||
// <script setup> compiler adds restoration:
|
||||
// After each await, it injects: setCurrentInstance(savedInstance)
|
||||
```
|
||||
|
||||
## Suspense Requirement
|
||||
|
||||
```vue
|
||||
<!-- When using async script setup, parent needs Suspense -->
|
||||
<template>
|
||||
<Suspense>
|
||||
<!-- Async component with top-level await -->
|
||||
<AsyncChild />
|
||||
|
||||
<!-- Optional: Loading state -->
|
||||
<template #fallback>
|
||||
<LoadingSpinner />
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Composition API FAQ - Async Setup](https://vuejs.org/guide/extras/composition-api-faq.html)
|
||||
- [Composables - Async Without Await](https://antfu.me/posts/async-with-composition-api)
|
||||
- [Suspense](https://vuejs.org/guide/built-ins/suspense.html)
|
||||
@@ -0,0 +1,156 @@
|
||||
---
|
||||
title: Vue Composition API Runs Once, Unlike React Hooks
|
||||
impact: MEDIUM
|
||||
impactDescription: Understanding this difference prevents over-engineering and React patterns that don't apply
|
||||
type: gotcha
|
||||
tags: [vue3, composition-api, react-hooks, setup, stale-closure]
|
||||
---
|
||||
|
||||
# Vue Composition API Runs Once, Unlike React Hooks
|
||||
|
||||
**Impact: MEDIUM** - Vue's `setup()` or `<script setup>` executes only once per component instance, while React Hooks run on every render. Developers coming from React often apply patterns (dependency arrays, excessive memoization, useCallback) that are unnecessary and counterproductive in Vue.
|
||||
|
||||
Understanding this fundamental difference is crucial for writing idiomatic Vue code. Vue's approach eliminates entire categories of bugs (stale closures, exhaustive deps) that plague React applications.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Don't implement "dependency arrays" - Vue tracks dependencies automatically
|
||||
- [ ] Don't wrap functions in "useCallback" equivalents - not needed in Vue
|
||||
- [ ] Don't use "useMemo" patterns - Vue's `computed()` handles this automatically
|
||||
- [ ] Understand that closures in Vue don't go "stale" like in React
|
||||
- [ ] Don't worry about "call order" - Vue composables can be conditional
|
||||
|
||||
**React Patterns to Avoid in Vue:**
|
||||
```javascript
|
||||
// These patterns are UNNECESSARY in Vue - they solve React-specific problems
|
||||
|
||||
// WRONG: Trying to implement dependency arrays (React pattern)
|
||||
watch(
|
||||
[dep1, dep2, dep3], // Vue tracks deps automatically in watchEffect
|
||||
() => {
|
||||
// ...
|
||||
}
|
||||
)
|
||||
// Unless you specifically WANT to control which deps trigger the watcher,
|
||||
// prefer watchEffect() which auto-tracks
|
||||
|
||||
// WRONG: Memoizing callbacks like useCallback
|
||||
const memoizedHandler = computed(() => {
|
||||
return () => doSomething(state.value)
|
||||
})
|
||||
// In Vue, just define the function normally - no memoization needed
|
||||
|
||||
// WRONG: Worrying about stale closures
|
||||
function useData() {
|
||||
const data = ref(null)
|
||||
|
||||
// In React, this could capture stale 'data' - NOT in Vue!
|
||||
// Vue refs are always current
|
||||
const handler = () => {
|
||||
console.log(data.value) // Always gets current value
|
||||
}
|
||||
|
||||
return { data, handler }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct Vue Patterns:**
|
||||
```javascript
|
||||
import { ref, computed, watchEffect } from 'vue'
|
||||
|
||||
// CORRECT: Auto-dependency tracking with watchEffect
|
||||
const query = ref('')
|
||||
const filter = ref('all')
|
||||
|
||||
watchEffect(() => {
|
||||
// Vue automatically detects that this depends on query and filter
|
||||
// No dependency array needed!
|
||||
fetchResults(query.value, filter.value)
|
||||
})
|
||||
|
||||
// CORRECT: computed() handles memoization automatically
|
||||
const expensiveResult = computed(() => {
|
||||
// Only recalculates when dependencies actually change
|
||||
return heavyComputation(data.value)
|
||||
})
|
||||
|
||||
// CORRECT: Functions don't need memoization
|
||||
function handleClick() {
|
||||
count.value++
|
||||
}
|
||||
// Just use it directly - no useCallback wrapper needed
|
||||
// <button @click="handleClick">
|
||||
|
||||
// CORRECT: Closures always access current values
|
||||
const count = ref(0)
|
||||
const message = ref('')
|
||||
|
||||
function logState() {
|
||||
// This always logs CURRENT values, never stale ones
|
||||
console.log(`Count: ${count.value}, Message: ${message.value}`)
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
logState() // Gets current values even if called later
|
||||
}, 5000)
|
||||
```
|
||||
|
||||
## Vue's Advantages Over React Hooks
|
||||
|
||||
```javascript
|
||||
// 1. No stale closure problems
|
||||
const count = ref(0)
|
||||
|
||||
onMounted(() => {
|
||||
setInterval(() => {
|
||||
// In React: would need useRef or deps array to avoid stale value
|
||||
// In Vue: count.value is always current
|
||||
console.log(count.value)
|
||||
}, 1000)
|
||||
})
|
||||
|
||||
// 2. Composables can be conditional
|
||||
if (featureEnabled) {
|
||||
const { data } = useSomeFeature() // This is FINE in Vue!
|
||||
}
|
||||
// In React: "Hooks cannot be conditional" - not a problem in Vue
|
||||
|
||||
// 3. No exhaustive-deps linting headaches
|
||||
watchEffect(() => {
|
||||
// Use any reactive values - Vue tracks them all automatically
|
||||
// No ESLint rule yelling about missing dependencies
|
||||
doSomething(a.value, b.value, c.value)
|
||||
})
|
||||
|
||||
// 4. Child components don't need memoization by default
|
||||
// Vue's reactivity system only updates what actually changed
|
||||
// No need for React.memo() equivalents in most cases
|
||||
```
|
||||
|
||||
## When Vue Patterns Differ
|
||||
|
||||
```javascript
|
||||
// Setup runs once - so initialization happens once
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
// This code runs ONCE when component is created
|
||||
const data = ref(null)
|
||||
console.log('Setup running') // Only logs once
|
||||
|
||||
onMounted(() => {
|
||||
console.log('Mounted') // Only logs once
|
||||
})
|
||||
|
||||
// If you need something to run on every reactive change,
|
||||
// use watch or watchEffect
|
||||
watchEffect(() => {
|
||||
// This runs when dependencies change
|
||||
console.log('Data changed:', data.value)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Composition API FAQ - Relationship with React Hooks](https://vuejs.org/guide/extras/composition-api-faq.html#relationship-with-react-hooks)
|
||||
- [Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
title: Avoid Mutating Methods on Arrays in Computed Properties
|
||||
impact: HIGH
|
||||
impactDescription: Array mutating methods in computed modify source data causing unexpected behavior
|
||||
type: capability
|
||||
tags: [vue3, computed, arrays, mutation, sort, reverse]
|
||||
---
|
||||
|
||||
# Avoid Mutating Methods on Arrays in Computed Properties
|
||||
|
||||
**Impact: HIGH** - JavaScript array methods like `reverse()`, `sort()`, `splice()`, `push()`, `pop()`, `shift()`, and `unshift()` mutate the original array. Using them directly on reactive arrays inside computed properties will modify your source data, causing unexpected side effects and bugs.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Always create a copy of arrays before using mutating methods
|
||||
- [ ] Use spread operator `[...array]` or `slice()` to copy arrays
|
||||
- [ ] Prefer non-mutating alternatives when available
|
||||
- [ ] Be aware which array methods mutate vs return new arrays
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([3, 1, 4, 1, 5, 9, 2, 6])
|
||||
const users = ref([
|
||||
{ name: 'Alice', age: 30 },
|
||||
{ name: 'Bob', age: 25 }
|
||||
])
|
||||
|
||||
// BAD: sort() mutates the original array!
|
||||
const sortedItems = computed(() => {
|
||||
return items.value.sort((a, b) => a - b)
|
||||
})
|
||||
|
||||
// BAD: reverse() mutates the original array!
|
||||
const reversedItems = computed(() => {
|
||||
return items.value.reverse()
|
||||
})
|
||||
|
||||
// BAD: Both arrays now point to the same mutated data
|
||||
// items.value and sortedItems.value are the SAME array
|
||||
// items.value and reversedItems.value are the SAME array
|
||||
|
||||
// BAD: Chained mutations
|
||||
const sortedUsers = computed(() => {
|
||||
return users.value.sort((a, b) => a.age - b.age)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Original array is corrupted! -->
|
||||
<div>Original: {{ items }}</div>
|
||||
<div>Sorted: {{ sortedItems }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([3, 1, 4, 1, 5, 9, 2, 6])
|
||||
const users = ref([
|
||||
{ name: 'Alice', age: 30 },
|
||||
{ name: 'Bob', age: 25 }
|
||||
])
|
||||
|
||||
// GOOD: Spread operator creates a copy first
|
||||
const sortedItems = computed(() => {
|
||||
return [...items.value].sort((a, b) => a - b)
|
||||
})
|
||||
|
||||
// GOOD: slice() also creates a copy
|
||||
const reversedItems = computed(() => {
|
||||
return items.value.slice().reverse()
|
||||
})
|
||||
|
||||
// GOOD: Copy before sorting objects
|
||||
const sortedUsers = computed(() => {
|
||||
return [...users.value].sort((a, b) => a.age - b.age)
|
||||
})
|
||||
|
||||
// GOOD: Use toSorted() (ES2023) - non-mutating
|
||||
const sortedItemsModern = computed(() => {
|
||||
return items.value.toSorted((a, b) => a - b)
|
||||
})
|
||||
|
||||
// GOOD: Use toReversed() (ES2023) - non-mutating
|
||||
const reversedItemsModern = computed(() => {
|
||||
return items.value.toReversed()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Original array stays intact -->
|
||||
<div>Original: {{ items }}</div>
|
||||
<div>Sorted: {{ sortedItems }}</div>
|
||||
<div>Reversed: {{ reversedItems }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Mutating vs Non-Mutating Array Methods
|
||||
|
||||
| Mutating (Avoid in Computed) | Non-Mutating (Safe) |
|
||||
|------------------------------|---------------------|
|
||||
| `sort()` | `toSorted()` (ES2023) |
|
||||
| `reverse()` | `toReversed()` (ES2023) |
|
||||
| `splice()` | `toSpliced()` (ES2023) |
|
||||
| `push()` | `concat()` |
|
||||
| `pop()` | `slice(0, -1)` |
|
||||
| `shift()` | `slice(1)` |
|
||||
| `unshift()` | `[item, ...array]` |
|
||||
| `fill()` | `map()` with new values |
|
||||
|
||||
## ES2023 Non-Mutating Alternatives
|
||||
|
||||
Modern JavaScript (ES2023) provides non-mutating versions of common array methods:
|
||||
|
||||
```javascript
|
||||
// These return NEW arrays, safe for computed properties
|
||||
const sorted = array.toSorted((a, b) => a - b)
|
||||
const reversed = array.toReversed()
|
||||
const spliced = array.toSpliced(1, 2, 'new')
|
||||
const withReplaced = array.with(0, 'newFirst')
|
||||
```
|
||||
|
||||
## Deep Copy for Nested Arrays
|
||||
|
||||
For arrays of objects where you might mutate nested properties:
|
||||
|
||||
```javascript
|
||||
const items = ref([{ name: 'A', values: [1, 2, 3] }])
|
||||
|
||||
// Shallow copy - nested arrays still shared
|
||||
const copied = computed(() => [...items.value])
|
||||
|
||||
// Deep copy if you need to mutate nested structures
|
||||
const deepCopied = computed(() => {
|
||||
return JSON.parse(JSON.stringify(items.value))
|
||||
// Or use structuredClone():
|
||||
// return structuredClone(items.value)
|
||||
})
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Computed Properties - Avoid Mutating Computed Value](https://vuejs.org/guide/essentials/computed.html#avoid-mutating-computed-value)
|
||||
- [MDN Array Methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
|
||||
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: Ensure All Dependencies Are Accessed in Computed Properties
|
||||
impact: HIGH
|
||||
impactDescription: Conditional logic can prevent dependency tracking causing stale computed values
|
||||
type: capability
|
||||
tags: [vue3, computed, reactivity, dependency-tracking, gotcha]
|
||||
---
|
||||
|
||||
# Ensure All Dependencies Are Accessed in Computed Properties
|
||||
|
||||
**Impact: HIGH** - Vue tracks computed property dependencies by monitoring which reactive properties are accessed during execution. If conditional logic prevents a property from being accessed on the first run, Vue won't track it as a dependency, causing the computed property to not update when that property changes.
|
||||
|
||||
This is a subtle but common source of bugs, especially with short-circuit evaluation (`&&`, `||`) and early returns.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Access all reactive dependencies before any conditional logic
|
||||
- [ ] Be cautious with short-circuit operators (`&&`, `||`) that may skip property access
|
||||
- [ ] Store all dependencies in variables at the start of the computed getter
|
||||
- [ ] Test computed properties with different initial states
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const isEnabled = ref(false)
|
||||
const data = ref('important data')
|
||||
|
||||
// BAD: If isEnabled is false initially, data.value is never accessed
|
||||
// Vue won't track 'data' as a dependency!
|
||||
const result = computed(() => {
|
||||
if (!isEnabled.value) {
|
||||
return 'disabled'
|
||||
}
|
||||
return data.value // This dependency may not be tracked
|
||||
})
|
||||
|
||||
// BAD: Short-circuit prevents second access
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
|
||||
const isValid = computed(() => {
|
||||
// If password is empty, confirmPassword is never accessed
|
||||
return password.value && password.value === confirmPassword.value
|
||||
})
|
||||
|
||||
// BAD: Early return prevents dependency access
|
||||
const user = ref(null)
|
||||
const permissions = ref(['read', 'write'])
|
||||
|
||||
const canEdit = computed(() => {
|
||||
if (!user.value) {
|
||||
return false // permissions.value never accessed when user is null
|
||||
}
|
||||
return permissions.value.includes('write')
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const isEnabled = ref(false)
|
||||
const data = ref('important data')
|
||||
|
||||
// GOOD: Access all dependencies first
|
||||
const result = computed(() => {
|
||||
const enabled = isEnabled.value
|
||||
const currentData = data.value // Always accessed
|
||||
|
||||
if (!enabled) {
|
||||
return 'disabled'
|
||||
}
|
||||
return currentData
|
||||
})
|
||||
|
||||
// GOOD: Access both values before comparison
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
|
||||
const isValid = computed(() => {
|
||||
const pwd = password.value
|
||||
const confirm = confirmPassword.value // Always accessed
|
||||
|
||||
return pwd && pwd === confirm
|
||||
})
|
||||
|
||||
// GOOD: Access all reactive sources upfront
|
||||
const user = ref(null)
|
||||
const permissions = ref(['read', 'write'])
|
||||
|
||||
const canEdit = computed(() => {
|
||||
const currentUser = user.value
|
||||
const currentPermissions = permissions.value // Always accessed
|
||||
|
||||
if (!currentUser) {
|
||||
return false
|
||||
}
|
||||
return currentPermissions.includes('write')
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## The Dependency Tracking Mechanism
|
||||
|
||||
Vue's reactivity system works by tracking which reactive properties are accessed when a computed property runs:
|
||||
|
||||
```javascript
|
||||
// How Vue tracks dependencies (simplified):
|
||||
// 1. Start tracking
|
||||
// 2. Run the getter function
|
||||
// 3. Record every .value or reactive property access
|
||||
// 4. Stop tracking
|
||||
|
||||
const computed = computed(() => {
|
||||
// Vue starts tracking here
|
||||
if (conditionA.value) { // conditionA is tracked
|
||||
return valueB.value // valueB is ONLY tracked if conditionA is true
|
||||
}
|
||||
return 'default' // If conditionA is false, valueB is NOT tracked!
|
||||
})
|
||||
```
|
||||
|
||||
## Pattern: Destructure All Dependencies First
|
||||
|
||||
```javascript
|
||||
// GOOD PATTERN: Destructure/access everything at the top
|
||||
const result = computed(() => {
|
||||
// Access all potential dependencies
|
||||
const { user, settings, items } = toRefs(store)
|
||||
const userVal = user.value
|
||||
const settingsVal = settings.value
|
||||
const itemsVal = items.value
|
||||
|
||||
// Now use conditional logic safely
|
||||
if (!userVal) return []
|
||||
if (!settingsVal.enabled) return []
|
||||
return itemsVal.filter(i => i.active)
|
||||
})
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Reactivity in Depth](https://vuejs.org/guide/extras/reactivity-in-depth.html)
|
||||
- [GitHub Discussion: Dependency collection gotcha with conditionals](https://github.com/vuejs/Discussion/issues/15)
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
title: Computed Properties Cannot Accept Parameters
|
||||
impact: MEDIUM
|
||||
impactDescription: Attempting to pass arguments to computed properties fails or defeats caching
|
||||
type: capability
|
||||
tags: [vue3, computed, methods, parameters, common-mistake]
|
||||
---
|
||||
|
||||
# Computed Properties Cannot Accept Parameters
|
||||
|
||||
**Impact: MEDIUM** - Computed properties are designed to derive values from reactive state without parameters. Attempting to pass arguments defeats the caching mechanism or causes errors. Use methods or computed properties that return functions instead.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use methods when you need to pass parameters
|
||||
- [ ] Consider if the parameter can be reactive state instead
|
||||
- [ ] If you must parameterize, understand that returning a function loses caching benefits
|
||||
- [ ] Prefer method calls in templates for parameterized operations
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- BAD: Computed properties don't accept parameters like this -->
|
||||
<p>{{ filteredItems('active') }}</p>
|
||||
<p>{{ formattedPrice(100, 'USD') }}</p>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([/* ... */])
|
||||
|
||||
// BAD: This won't work as expected
|
||||
// Computed is called once, not per parameter
|
||||
const filteredItems = computed((status) => { // status will be undefined or previous value
|
||||
return items.value.filter(i => i.status === status)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return { items: [/* ... */] }
|
||||
},
|
||||
computed: {
|
||||
// BAD: Computed doesn't receive arguments
|
||||
filteredItems(status) { // 'status' is actually 'this' or undefined
|
||||
return this.items.filter(i => i.status === status)
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Use method for parameterized operations -->
|
||||
<p>{{ getFilteredItems('active') }}</p>
|
||||
<p>{{ formatPrice(100, 'USD') }}</p>
|
||||
|
||||
<!-- GOOD: Or use computed with reactive filter state -->
|
||||
<select v-model="statusFilter">
|
||||
<option value="active">Active</option>
|
||||
<option value="inactive">Inactive</option>
|
||||
</select>
|
||||
<p>{{ filteredItems }}</p>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([/* ... */])
|
||||
const statusFilter = ref('active')
|
||||
|
||||
// GOOD: Method for parameterized operations
|
||||
function getFilteredItems(status) {
|
||||
return items.value.filter(i => i.status === status)
|
||||
}
|
||||
|
||||
function formatPrice(amount, currency) {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency
|
||||
}).format(amount)
|
||||
}
|
||||
|
||||
// GOOD: Computed with reactive parameter
|
||||
const filteredItems = computed(() => {
|
||||
return items.value.filter(i => i.status === statusFilter.value)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Workaround: Computed Returning a Function
|
||||
|
||||
If you need something computed-like with parameters, you can return a function. **However, this defeats the caching benefit:**
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<p>{{ getItemsByStatus('active') }}</p>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([/* ... */])
|
||||
|
||||
// This works but provides NO caching benefit
|
||||
// The inner function runs every time it's called
|
||||
const getItemsByStatus = computed(() => {
|
||||
return (status) => items.value.filter(i => i.status === status)
|
||||
})
|
||||
|
||||
// This is essentially equivalent to just using a method
|
||||
// Only useful if you need to compose with other computed properties
|
||||
</script>
|
||||
```
|
||||
|
||||
## When to Use Each Approach
|
||||
|
||||
| Scenario | Approach | Caching |
|
||||
|----------|----------|---------|
|
||||
| Fixed filter based on reactive state | Computed | Yes |
|
||||
| Dynamic filter passed as argument | Method | No |
|
||||
| Filter options from user selection | Computed + reactive param | Yes |
|
||||
| Formatting with variable parameters | Method | No |
|
||||
| Composed derivation with argument | Computed returning function | Partial |
|
||||
|
||||
## Make Parameters Reactive
|
||||
|
||||
The best pattern is often to make the "parameter" a reactive value:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([/* ... */])
|
||||
|
||||
// Instead of passing 'status' as a parameter:
|
||||
const currentStatus = ref('active')
|
||||
|
||||
// Make a computed that uses the reactive status
|
||||
const filteredItems = computed(() => {
|
||||
return items.value.filter(i => i.status === currentStatus.value)
|
||||
})
|
||||
|
||||
// Change the filter by updating the ref
|
||||
function filterByStatus(status) {
|
||||
currentStatus.value = status
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html)
|
||||
- [Vue.js Methods](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#declaring-methods)
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
title: Computed Property Getters Must Be Side-Effect Free
|
||||
impact: HIGH
|
||||
impactDescription: Side effects in computed getters break reactivity and cause unpredictable behavior
|
||||
type: efficiency
|
||||
tags: [vue3, computed, reactivity, side-effects, best-practices]
|
||||
---
|
||||
|
||||
# Computed Property Getters Must Be Side-Effect Free
|
||||
|
||||
**Impact: HIGH** - Computed getter functions should only perform pure computation. Side effects in computed getters break Vue's reactivity model and cause bugs that are difficult to trace.
|
||||
|
||||
Computed properties are designed to declaratively describe how to derive a value from other reactive state. They are not meant to perform actions or modify state.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Never mutate other reactive state inside a computed getter
|
||||
- [ ] Never make async requests or API calls inside a computed getter
|
||||
- [ ] Never perform DOM mutations inside a computed getter
|
||||
- [ ] Use watchers for reacting to state changes with side effects
|
||||
- [ ] Use event handlers for user-triggered actions
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const items = ref([])
|
||||
const count = ref(0)
|
||||
const lastFetch = ref(null)
|
||||
|
||||
// BAD: Mutates other state
|
||||
const doubledCount = computed(() => {
|
||||
count.value++ // Side effect - modifying state!
|
||||
return count.value * 2
|
||||
})
|
||||
|
||||
// BAD: Makes async request
|
||||
const userData = computed(async () => {
|
||||
const response = await fetch('/api/user') // Side effect - API call!
|
||||
return response.json()
|
||||
})
|
||||
|
||||
// BAD: Modifies DOM
|
||||
const highlightedItems = computed(() => {
|
||||
document.title = `${items.value.length} items` // Side effect - DOM mutation!
|
||||
return items.value.filter(i => i.highlighted)
|
||||
})
|
||||
|
||||
// BAD: Writes to external state
|
||||
const processedData = computed(() => {
|
||||
lastFetch.value = new Date() // Side effect - modifying state!
|
||||
return items.value.map(i => i.name)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed, watch, onMounted } from 'vue'
|
||||
|
||||
const items = ref([])
|
||||
const count = ref(0)
|
||||
const userData = ref(null)
|
||||
|
||||
// GOOD: Pure computation only
|
||||
const doubledCount = computed(() => {
|
||||
return count.value * 2
|
||||
})
|
||||
|
||||
// GOOD: Use lifecycle hook for initial fetch
|
||||
onMounted(async () => {
|
||||
const response = await fetch('/api/user')
|
||||
userData.value = await response.json()
|
||||
})
|
||||
|
||||
// GOOD: Pure filtering
|
||||
const highlightedItems = computed(() => {
|
||||
return items.value.filter(i => i.highlighted)
|
||||
})
|
||||
|
||||
// GOOD: Use watcher for side effects
|
||||
watch(items, (newItems) => {
|
||||
document.title = `${newItems.length} items`
|
||||
}, { immediate: true })
|
||||
|
||||
// Increment count through event handler, not computed
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## What Counts as a Side Effect
|
||||
|
||||
| Side Effect Type | Example | Alternative |
|
||||
|-----------------|---------|-------------|
|
||||
| State mutation | `otherRef.value = x` | Use watcher |
|
||||
| API calls | `fetch()`, `axios()` | Use watcher or lifecycle hook |
|
||||
| DOM manipulation | `document.title = x` | Use watcher |
|
||||
| Console logging | `console.log()` | Remove or use watcher |
|
||||
| Storage access | `localStorage.setItem()` | Use watcher |
|
||||
| Timer setup | `setTimeout()` | Use lifecycle hook |
|
||||
|
||||
## Reference
|
||||
- [Vue.js Computed Properties - Getters Should Be Side-Effect Free](https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free)
|
||||
@@ -0,0 +1,160 @@
|
||||
---
|
||||
title: Never Mutate Computed Property Return Values
|
||||
impact: HIGH
|
||||
impactDescription: Mutating computed values causes silent failures and lost changes
|
||||
type: capability
|
||||
tags: [vue3, computed, reactivity, immutability, common-mistake]
|
||||
---
|
||||
|
||||
# Never Mutate Computed Property Return Values
|
||||
|
||||
**Impact: HIGH** - The returned value from a computed property is derived state - a temporary snapshot. Mutating this value leads to bugs that are difficult to debug.
|
||||
|
||||
**Important:** Mutations DO persist while the computed cache remains valid, but are lost when recomputation occurs. The danger lies in unpredictable cache invalidation timing - any change to the computed's dependencies triggers recomputation, silently discarding your mutations. This makes bugs intermittent and hard to reproduce.
|
||||
|
||||
Every time the source state changes, a new snapshot is created. Mutating a snapshot is meaningless because it will be discarded on the next recalculation.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Treat computed return values as read-only
|
||||
- [ ] Update the source state instead of the computed value
|
||||
- [ ] Use writable computed properties if bidirectional binding is needed
|
||||
- [ ] Avoid array mutating methods (push, pop, splice, reverse, sort) on computed arrays
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const books = ref(['Vue Guide', 'React Handbook'])
|
||||
|
||||
const publishedBooks = computed(() => {
|
||||
return books.value.filter(book => book.includes('Guide'))
|
||||
})
|
||||
|
||||
function addBook() {
|
||||
// BAD: Mutating computed value - change will be lost!
|
||||
publishedBooks.value.push('New Book')
|
||||
}
|
||||
|
||||
// BAD: Mutating computed array
|
||||
const sortedBooks = computed(() => books.value.filter(b => b))
|
||||
|
||||
function reverseBooks() {
|
||||
// BAD: This mutates the computed snapshot
|
||||
sortedBooks.value.reverse()
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
author: {
|
||||
name: 'John',
|
||||
books: ['Book A', 'Book B']
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
authorBooks() {
|
||||
return this.author.books
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
addBook() {
|
||||
// BAD: Mutating computed value
|
||||
this.authorBooks.push('New Book')
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const books = ref(['Vue Guide', 'React Handbook'])
|
||||
|
||||
const publishedBooks = computed(() => {
|
||||
return books.value.filter(book => book.includes('Guide'))
|
||||
})
|
||||
|
||||
function addBook(bookName) {
|
||||
// GOOD: Update the source state
|
||||
books.value.push(bookName)
|
||||
}
|
||||
|
||||
// GOOD: Create a copy before mutating for display
|
||||
const sortedBooks = computed(() => {
|
||||
return [...books.value].sort() // Spread to create copy before sort
|
||||
})
|
||||
|
||||
const reversedBooks = computed(() => {
|
||||
return [...books.value].reverse() // Spread to create copy before reverse
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
author: {
|
||||
name: 'John',
|
||||
books: ['Book A', 'Book B']
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
authorBooks() {
|
||||
return this.author.books
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
addBook(bookName) {
|
||||
// GOOD: Update source state
|
||||
this.author.books.push(bookName)
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Writable Computed for Bidirectional Binding
|
||||
|
||||
If you genuinely need to "set" a computed value, use a writable computed property:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const firstName = ref('John')
|
||||
const lastName = ref('Doe')
|
||||
|
||||
// Writable computed with getter and setter
|
||||
const fullName = computed({
|
||||
get() {
|
||||
return `${firstName.value} ${lastName.value}`
|
||||
},
|
||||
set(newValue) {
|
||||
// Update source state based on the new value
|
||||
const parts = newValue.split(' ')
|
||||
firstName.value = parts[0] || ''
|
||||
lastName.value = parts[1] || ''
|
||||
}
|
||||
})
|
||||
|
||||
// Now this is valid:
|
||||
fullName.value = 'Jane Smith' // Updates firstName and lastName
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Computed Properties - Avoid Mutating Computed Value](https://vuejs.org/guide/essentials/computed.html#avoid-mutating-computed-value)
|
||||
- [Vue.js Computed Properties - Writable Computed](https://vuejs.org/guide/essentials/computed.html#writable-computed)
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
title: Configure Vue App Before Calling mount()
|
||||
impact: HIGH
|
||||
impactDescription: App configurations after mount() are silently ignored, causing missing plugins and handlers
|
||||
type: capability
|
||||
tags: [vue3, createApp, mount, configuration, setup]
|
||||
---
|
||||
|
||||
# Configure Vue App Before Calling mount()
|
||||
|
||||
**Impact: HIGH** - Any app configurations applied after `.mount()` is called are silently ignored. This includes error handlers, global components, directives, and plugins, leading to mysterious missing functionality.
|
||||
|
||||
The `.mount()` method should always be called after all app configurations and asset registrations are done. This is a critical ordering requirement that, when violated, produces no errors but causes features to silently fail.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Register all plugins (router, store, etc.) before mount()
|
||||
- [ ] Configure error handlers before mount()
|
||||
- [ ] Register global components and directives before mount()
|
||||
- [ ] Set all `app.config` properties before mount()
|
||||
- [ ] Call `.mount()` as the final step in app initialization
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// WRONG: Mounting first, then configuring
|
||||
app.mount('#app')
|
||||
|
||||
// These are silently IGNORED - app is already mounted!
|
||||
app.use(router)
|
||||
app.config.errorHandler = (err) => {
|
||||
console.error('Global error:', err)
|
||||
}
|
||||
app.component('GlobalButton', GlobalButton)
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { createPinia } from 'pinia'
|
||||
import GlobalButton from './components/GlobalButton.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// Configure everything FIRST
|
||||
app.use(router)
|
||||
app.use(createPinia())
|
||||
|
||||
// Set up error handling
|
||||
app.config.errorHandler = (err, instance, info) => {
|
||||
console.error('Global error:', err)
|
||||
console.log('Component:', instance)
|
||||
console.log('Error info:', info)
|
||||
}
|
||||
|
||||
// Register global components
|
||||
app.component('GlobalButton', GlobalButton)
|
||||
|
||||
// Mount LAST - after all configuration is complete
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## Common Mistake: Chaining with Mount
|
||||
|
||||
```javascript
|
||||
// WRONG: Chaining mount in the middle of configuration
|
||||
createApp(App)
|
||||
.use(router)
|
||||
.mount('#app') // Everything after this line is a problem
|
||||
.use(pinia) // This doesn't even work - mount returns component instance!
|
||||
|
||||
// CORRECT: Either complete chain before mount, or use intermediate variable
|
||||
createApp(App)
|
||||
.use(router)
|
||||
.use(pinia)
|
||||
.component('GlobalButton', GlobalButton)
|
||||
.mount('#app') // Mount at the very end
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js - Creating a Vue Application](https://vuejs.org/guide/essentials/application.html)
|
||||
- [Vue.js Application API](https://vuejs.org/api/application.html)
|
||||
@@ -0,0 +1,212 @@
|
||||
---
|
||||
title: Always Declare Emits for Documentation and Validation
|
||||
impact: MEDIUM
|
||||
impactDescription: Undeclared emits cause warnings, break TypeScript inference, and prevent event validation
|
||||
type: best-practice
|
||||
tags: [vue3, emits, defineEmits, component-events, typescript, documentation]
|
||||
---
|
||||
|
||||
# Always Declare Emits for Documentation and Validation
|
||||
|
||||
**Impact: MEDIUM** - Declaring emitted events with `defineEmits()` or the `emits` option is technically optional, but strongly recommended. Without declarations, Vue shows runtime warnings, TypeScript can't infer event types, and you lose the ability to validate event payloads.
|
||||
|
||||
Declared emits also serve as self-documentation, making it immediately clear what events a component can emit.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use `defineEmits()` in `<script setup>` to declare all events
|
||||
- [ ] Use `emits` option when not using `<script setup>`
|
||||
- [ ] Add TypeScript types for event payloads
|
||||
- [ ] Consider adding validation functions for complex payloads
|
||||
- [ ] Document the purpose of each event
|
||||
|
||||
## The Warning
|
||||
|
||||
When you emit without declaring:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// No defineEmits declaration
|
||||
function handleClick() {
|
||||
emit('select', item) // Vue warns in dev mode
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
Vue warns:
|
||||
```
|
||||
[Vue warn]: Component emitted event "select" but it is neither declared
|
||||
in the emits option nor as an "onSelect" prop.
|
||||
```
|
||||
|
||||
## Basic Declaration
|
||||
|
||||
**Correct - Array syntax:**
|
||||
```vue
|
||||
<script setup>
|
||||
const emit = defineEmits(['submit', 'cancel', 'update'])
|
||||
|
||||
function handleSubmit() {
|
||||
emit('submit', formData)
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
emit('cancel')
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct - Options API:**
|
||||
```js
|
||||
export default {
|
||||
emits: ['submit', 'cancel', 'update'],
|
||||
|
||||
methods: {
|
||||
handleSubmit() {
|
||||
this.$emit('submit', this.formData)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## TypeScript Typed Emits
|
||||
|
||||
**Correct - Type-based declaration (recommended for TypeScript):**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface User {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
const emit = defineEmits<{
|
||||
submit: [data: FormData]
|
||||
cancel: []
|
||||
'update:modelValue': [value: string]
|
||||
select: [user: User, index: number]
|
||||
}>()
|
||||
|
||||
// Now TypeScript enforces correct payloads
|
||||
emit('submit', formData) // OK
|
||||
emit('submit') // Error: Expected 1 argument
|
||||
emit('select', user) // Error: Expected 2 arguments
|
||||
emit('unknown') // Error: Unknown event
|
||||
</script>
|
||||
```
|
||||
|
||||
**Alternative syntax (Vue 3.3+):**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const emit = defineEmits<{
|
||||
(e: 'submit', data: FormData): void
|
||||
(e: 'cancel'): void
|
||||
(e: 'update:modelValue', value: string): void
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Event Validation
|
||||
|
||||
You can validate event payloads at runtime:
|
||||
|
||||
**Correct - Validation functions:**
|
||||
```vue
|
||||
<script setup>
|
||||
const emit = defineEmits({
|
||||
// No validation, just declaration
|
||||
cancel: null,
|
||||
|
||||
// Validate payload
|
||||
submit: (payload) => {
|
||||
if (!payload.email) {
|
||||
console.warn('Submit event requires email')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
|
||||
// Validate with type checking
|
||||
click: (id) => typeof id === 'number'
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
Returning `false` from a validator logs a console warning but doesn't prevent the event from being emitted.
|
||||
|
||||
## Benefits of Declaring Emits
|
||||
|
||||
### 1. Fallthrough Attribute Separation
|
||||
|
||||
Without declaration, native event listeners fall through to the root element:
|
||||
|
||||
```vue
|
||||
<!-- ParentComponent.vue -->
|
||||
<ChildComponent @click="handleClick" />
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ChildComponent.vue - WITHOUT emits declaration -->
|
||||
<template>
|
||||
<!-- Native click listener falls through to button -->
|
||||
<button>Click me</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
With declaration, Vue knows it's a component event:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// Now Vue knows 'click' is a component event, not native
|
||||
const emit = defineEmits(['click'])
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2. Self-Documentation
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// Clear contract: this component emits these events
|
||||
const emit = defineEmits<{
|
||||
'row-click': [row: TableRow]
|
||||
'row-select': [row: TableRow, selected: boolean]
|
||||
'page-change': [page: number]
|
||||
'sort-change': [column: string, direction: 'asc' | 'desc']
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
### 3. IDE Support
|
||||
|
||||
With declarations, your IDE can:
|
||||
- Autocomplete event names when using the component
|
||||
- Show event payload types
|
||||
- Warn about typos in event names
|
||||
- Navigate to event definitions
|
||||
|
||||
## $emit in Template vs emit in Script
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// $emit is available in template, but...
|
||||
// emit() is needed in <script setup>
|
||||
const emit = defineEmits(['submit'])
|
||||
|
||||
function handleSubmit() {
|
||||
// $emit doesn't work here - use emit()
|
||||
emit('submit', data)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- $emit works in template -->
|
||||
<button @click="$emit('submit', data)">Submit</button>
|
||||
|
||||
<!-- Or use the declared emit function -->
|
||||
<button @click="emit('submit', data)">Submit</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component Events - Declaring Emitted Events](https://vuejs.org/guide/components/events.html#declaring-emitted-events)
|
||||
- [Vue.js Component Events - Events Validation](https://vuejs.org/guide/components/events.html#events-validation)
|
||||
- [Vue 3 Migration - emits Option](https://v3-migration.vuejs.org/breaking-changes/emits-option)
|
||||
@@ -0,0 +1,192 @@
|
||||
---
|
||||
title: defineExpose Must Be Called Before Any Await
|
||||
impact: HIGH
|
||||
impactDescription: Properties exposed after await are inaccessible to parent component refs
|
||||
type: gotcha
|
||||
tags: [vue3, script-setup, defineExpose, async, component-refs]
|
||||
---
|
||||
|
||||
# defineExpose Must Be Called Before Any Await
|
||||
|
||||
**Impact: HIGH** - In `<script setup>`, if you call `defineExpose()` after an `await` statement, the exposed properties will NOT be accessible to parent components using template refs. This is a subtle async timing issue that causes silent failures.
|
||||
|
||||
The compiler transforms top-level await, and code after await runs in a different execution context where defineExpose cannot properly register with the component instance.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Always call defineExpose() at the top of script setup, before any await
|
||||
- [ ] If async data is needed in exposed methods, fetch it separately
|
||||
- [ ] Structure code so expose declarations come first
|
||||
- [ ] Test parent ref access when using async setup
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const data = ref(null)
|
||||
const count = ref(0)
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
// WRONG: await before defineExpose
|
||||
const response = await fetch('/api/data')
|
||||
data.value = await response.json()
|
||||
|
||||
// BROKEN: This won't work - called after await!
|
||||
defineExpose({
|
||||
count,
|
||||
increment,
|
||||
data
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>{{ data }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
|
||||
const childRef = ref(null)
|
||||
|
||||
onMounted(() => {
|
||||
// FAILS: All exposed properties are undefined!
|
||||
console.log(childRef.value.count) // undefined
|
||||
childRef.value.increment() // TypeError
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Suspense>
|
||||
<ChildComponent ref="childRef" />
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const data = ref(null)
|
||||
const count = ref(0)
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
// CORRECT: defineExpose BEFORE any await
|
||||
defineExpose({
|
||||
count,
|
||||
increment,
|
||||
data
|
||||
})
|
||||
|
||||
// Now safe to use await
|
||||
const response = await fetch('/api/data')
|
||||
data.value = await response.json()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>{{ data }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Alternative: Separate async logic from expose -->
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const data = ref(null)
|
||||
const loading = ref(true)
|
||||
|
||||
function getData() {
|
||||
return data.value
|
||||
}
|
||||
|
||||
async function refreshData() {
|
||||
loading.value = true
|
||||
const response = await fetch('/api/data')
|
||||
data.value = await response.json()
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
// CORRECT: No await at top level - defineExpose always works
|
||||
defineExpose({
|
||||
data,
|
||||
getData,
|
||||
refreshData,
|
||||
loading
|
||||
})
|
||||
|
||||
// Trigger async load in lifecycle hook instead
|
||||
onMounted(() => {
|
||||
refreshData()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="loading">Loading...</div>
|
||||
<div v-else>{{ data }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- If you must use top-level await, define expose first -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const user = ref(null)
|
||||
const posts = ref([])
|
||||
|
||||
// CORRECT: All expose calls come first
|
||||
defineExpose({
|
||||
user,
|
||||
posts,
|
||||
refresh: () => loadData()
|
||||
})
|
||||
|
||||
// Now safe to await
|
||||
async function loadData() {
|
||||
const [userRes, postsRes] = await Promise.all([
|
||||
fetch('/api/user'),
|
||||
fetch('/api/posts')
|
||||
])
|
||||
user.value = await userRes.json()
|
||||
posts.value = await postsRes.json()
|
||||
}
|
||||
|
||||
// Top-level await after defineExpose is safe
|
||||
await loadData()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Why This Happens
|
||||
|
||||
Vue's compiler transforms `<script setup>` with top-level await into an async setup function. The component instance context is only available synchronously before the first await. After await, the execution resumes outside that context, making defineExpose ineffective.
|
||||
|
||||
```javascript
|
||||
// What the compiler roughly generates:
|
||||
async setup() {
|
||||
const count = ref(0)
|
||||
|
||||
// Context available here
|
||||
await fetch(...) // Suspends execution
|
||||
|
||||
// Context lost after resuming
|
||||
defineExpose({ count }) // Too late!
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Script Setup - defineExpose](https://vuejs.org/api/sfc-script-setup.html#defineexpose)
|
||||
- [Vue.js Async Components](https://vuejs.org/guide/components/async.html)
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: defineModel Default Value Can Cause Parent-Child Desync
|
||||
impact: HIGH
|
||||
impactDescription: Default values in defineModel don't sync back to parent, causing state inconsistency
|
||||
type: capability
|
||||
tags: [vue3, v-model, defineModel, components, props, two-way-binding]
|
||||
---
|
||||
|
||||
# defineModel Default Value Can Cause Parent-Child Desync
|
||||
|
||||
**Impact: HIGH** - When using `defineModel()` with a default value and the parent doesn't provide a value, the parent and child components will have different values. The parent's ref stays `undefined` while the child uses the default, breaking the two-way binding contract.
|
||||
|
||||
This subtle bug can cause confusing behavior where the parent component shows one value while the child shows another, and updates may not propagate correctly.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Always provide initial values from the parent when using v-model
|
||||
- [ ] Don't rely on defineModel defaults as the primary source of truth
|
||||
- [ ] If defaults are needed, also set them in the parent component
|
||||
- [ ] Test components with and without v-model props provided
|
||||
|
||||
**Problem - Parent and child out of sync:**
|
||||
```html
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
// Default value of 1 if parent doesn't provide value
|
||||
const model = defineModel({ default: 1 })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="model" type="number">
|
||||
<!-- Shows: 1 (from default) -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
|
||||
// PROBLEM: Parent ref is undefined, not synced with child's default
|
||||
const myValue = ref() // undefined
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChildComponent v-model="myValue" />
|
||||
|
||||
<!-- DESYNC: Child shows 1, but parent shows undefined -->
|
||||
<p>Parent value: {{ myValue }}</p> <!-- Shows: undefined -->
|
||||
|
||||
<!-- Even after child changes value, parent may not update correctly -->
|
||||
</template>
|
||||
```
|
||||
|
||||
**Solution 1 - Always provide initial value from parent:**
|
||||
```html
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
|
||||
// CORRECT: Parent provides the initial value
|
||||
const myValue = ref(1) // Match the expected default
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChildComponent v-model="myValue" />
|
||||
<p>Parent value: {{ myValue }}</p> <!-- Shows: 1, stays in sync -->
|
||||
</template>
|
||||
```
|
||||
|
||||
**Solution 2 - Child emits default on mount (if parent control not possible):**
|
||||
```html
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
const model = defineModel({ default: 1 })
|
||||
|
||||
// Sync default value back to parent on mount
|
||||
onMounted(() => {
|
||||
if (model.value === 1) { // Is using default
|
||||
// Force emit to sync parent
|
||||
model.value = 1
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="model" type="number">
|
||||
</template>
|
||||
```
|
||||
|
||||
**Solution 3 - Use required prop or explicit undefined handling:**
|
||||
```html
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
// Mark as required - TypeScript will warn if not provided
|
||||
const model = defineModel({ required: true })
|
||||
|
||||
// Or handle undefined explicitly
|
||||
const safeModel = computed({
|
||||
get: () => model.value ?? 1, // Provide fallback
|
||||
set: (val) => { model.value = val }
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="safeModel" type="number">
|
||||
</template>
|
||||
```
|
||||
|
||||
**Best Practice - Document expected initial values:**
|
||||
```html
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
/**
|
||||
* @prop modelValue - The numeric value (parent should initialize to 1 or desired default)
|
||||
*/
|
||||
const model = defineModel({
|
||||
type: Number,
|
||||
default: 1,
|
||||
// Adding validator helps catch issues in development
|
||||
validator: (value) => {
|
||||
if (value === undefined) {
|
||||
console.warn('ChildComponent: v-model value is undefined. Provide initial value from parent.')
|
||||
}
|
||||
return true
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component v-model](https://vuejs.org/guide/components/v-model.html)
|
||||
- [Vue School - defineModel Guide](https://vueschool.io/articles/vuejs-tutorials/v-model-and-definemodel-a-comprehensive-guide-to-two-way-binding-in-vue-js-3/)
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
title: defineEmits Must Be Used at Top Level of script setup
|
||||
impact: HIGH
|
||||
impactDescription: Using defineEmits inside functions causes compilation errors - macros must be at module scope
|
||||
type: gotcha
|
||||
tags: [vue3, defineEmits, script-setup, macros, composition-api]
|
||||
---
|
||||
|
||||
# defineEmits Must Be Used at Top Level of script setup
|
||||
|
||||
**Impact: HIGH** - The `defineEmits()` macro can only be used directly within `<script setup>` at the top level. It cannot be placed inside functions, conditionals, or any other nested scope. Vue's compiler hoists these macros to module scope during compilation.
|
||||
|
||||
This applies to all Vue macros: `defineProps`, `defineEmits`, `defineExpose`, `defineOptions`, and `defineSlots`.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Place `defineEmits()` directly in `<script setup>`, not inside functions
|
||||
- [ ] Do not wrap macro calls in conditionals or loops
|
||||
- [ ] Do not reference local variables in macro arguments
|
||||
- [ ] Store the emit function and reuse it throughout the component
|
||||
|
||||
## The Problem
|
||||
|
||||
**Incorrect - Inside a function:**
|
||||
```vue
|
||||
<script setup>
|
||||
function useEvents() {
|
||||
// ERROR: defineEmits cannot be used inside a function
|
||||
const emit = defineEmits(['submit', 'cancel'])
|
||||
return emit
|
||||
}
|
||||
|
||||
const emit = useEvents() // This fails at compile time
|
||||
</script>
|
||||
```
|
||||
|
||||
**Incorrect - Inside a conditional:**
|
||||
```vue
|
||||
<script setup>
|
||||
if (someCondition) {
|
||||
// ERROR: Cannot use defineEmits in conditional
|
||||
const emit = defineEmits(['eventA'])
|
||||
} else {
|
||||
const emit = defineEmits(['eventB'])
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Incorrect - Referencing local variables:**
|
||||
```vue
|
||||
<script setup>
|
||||
const eventNames = ['submit', 'cancel']
|
||||
|
||||
// ERROR: Cannot reference local variables
|
||||
const emit = defineEmits(eventNames)
|
||||
</script>
|
||||
```
|
||||
|
||||
## Correct Usage
|
||||
|
||||
**Correct - Top level declaration:**
|
||||
```vue
|
||||
<script setup>
|
||||
// CORRECT: defineEmits at top level of script setup
|
||||
const emit = defineEmits(['submit', 'cancel', 'update'])
|
||||
|
||||
function handleSubmit() {
|
||||
emit('submit', data)
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
emit('cancel')
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct - With TypeScript types:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// CORRECT: Type-based declaration at top level
|
||||
const emit = defineEmits<{
|
||||
submit: [data: FormData]
|
||||
cancel: []
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
|
||||
function handleSubmit(data: FormData) {
|
||||
emit('submit', data)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct - Using constant arrays (compile-time constant):**
|
||||
```vue
|
||||
<script setup>
|
||||
// CORRECT: Literal array is fine
|
||||
const emit = defineEmits(['submit', 'cancel'])
|
||||
</script>
|
||||
```
|
||||
|
||||
## Why This Restriction Exists
|
||||
|
||||
Vue's compiler processes `<script setup>` macros at compile time, not runtime. The arguments must be statically analyzable so Vue can:
|
||||
|
||||
1. Generate the correct component options
|
||||
2. Provide TypeScript type inference
|
||||
3. Enable IDE support for event autocompletion
|
||||
4. Validate emitted events
|
||||
|
||||
Since the macro is hoisted out of `<script setup>` during compilation, it cannot access anything that only exists at runtime.
|
||||
|
||||
## Using emit in Composables
|
||||
|
||||
If you want to share emit logic in a composable, pass the emit function as an argument:
|
||||
|
||||
**Correct - Pass emit to composable:**
|
||||
```vue
|
||||
<script setup>
|
||||
const emit = defineEmits(['submit', 'cancel', 'validate'])
|
||||
|
||||
// Pass emit to composable
|
||||
const { handleSubmit, handleCancel } = useFormEvents(emit)
|
||||
</script>
|
||||
```
|
||||
|
||||
```js
|
||||
// composables/useFormEvents.js
|
||||
export function useFormEvents(emit) {
|
||||
function handleSubmit(data) {
|
||||
emit('submit', data)
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
emit('cancel')
|
||||
}
|
||||
|
||||
return { handleSubmit, handleCancel }
|
||||
}
|
||||
```
|
||||
|
||||
## ESLint Rule
|
||||
|
||||
The `eslint-plugin-vue` provides the `vue/valid-define-emits` rule that catches these errors:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
export default [
|
||||
{
|
||||
rules: {
|
||||
'vue/valid-define-emits': 'error'
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
This rule reports:
|
||||
- `defineEmits` used inside functions
|
||||
- `defineEmits` referencing local variables
|
||||
- Multiple `defineEmits` calls in the same component
|
||||
- `defineEmits` used outside `<script setup>`
|
||||
|
||||
## Reference
|
||||
- [Vue.js SFC script setup](https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits)
|
||||
- [ESLint vue/valid-define-emits](https://eslint.vuejs.org/rules/valid-define-emits)
|
||||
@@ -0,0 +1,170 @@
|
||||
---
|
||||
title: Cannot Mix Runtime and Type Declarations in defineEmits
|
||||
impact: HIGH
|
||||
impactDescription: Using both array/object syntax AND TypeScript generics in defineEmits causes compile errors
|
||||
type: gotcha
|
||||
tags: [vue3, defineEmits, typescript, compilation-error, script-setup]
|
||||
---
|
||||
|
||||
# Cannot Mix Runtime and Type Declarations in defineEmits
|
||||
|
||||
**Impact: HIGH** - `defineEmits` supports two declaration styles: runtime (array/object syntax) and type-based (TypeScript generics). You CANNOT use both at the same time. Attempting to do so results in a compile-time error.
|
||||
|
||||
This is a common mistake when learning Vue 3 with TypeScript.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Choose ONE declaration style: runtime OR type-based
|
||||
- [ ] For TypeScript projects, prefer type-based declaration
|
||||
- [ ] For JavaScript projects, use runtime (array/object) declaration
|
||||
- [ ] Never pass arguments when using generic type parameter
|
||||
|
||||
## The Problem
|
||||
|
||||
**Incorrect - Mixing both styles:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// ERROR: Cannot use both type argument and runtime argument
|
||||
const emit = defineEmits<{
|
||||
submit: [data: FormData]
|
||||
}>(['submit']) // This array argument causes the error!
|
||||
</script>
|
||||
```
|
||||
|
||||
**Compiler error:**
|
||||
```
|
||||
defineEmits() cannot accept both type and non-type arguments at the same time.
|
||||
Use one or the other.
|
||||
```
|
||||
|
||||
**Also incorrect:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// ERROR: Same problem with object syntax
|
||||
const emit = defineEmits<{
|
||||
submit: [data: FormData]
|
||||
}>({
|
||||
submit: (data) => !!data
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Correct: Type-Based Declaration (TypeScript)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// CORRECT: Type argument only, no runtime argument
|
||||
const emit = defineEmits<{
|
||||
submit: [data: FormData]
|
||||
cancel: []
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
|
||||
emit('submit', formData) // TypeScript validates this
|
||||
emit('cancel')
|
||||
emit('unknown') // TypeScript error: unknown event
|
||||
</script>
|
||||
```
|
||||
|
||||
**Alternative call signature syntax:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const emit = defineEmits<{
|
||||
(e: 'submit', data: FormData): void
|
||||
(e: 'cancel'): void
|
||||
(e: 'update:modelValue', value: string): void
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Correct: Runtime Declaration (JavaScript or Simple Cases)
|
||||
|
||||
**Array syntax:**
|
||||
```vue
|
||||
<script setup>
|
||||
// CORRECT: Runtime array, no type argument
|
||||
const emit = defineEmits(['submit', 'cancel', 'update:modelValue'])
|
||||
|
||||
emit('submit', formData)
|
||||
emit('cancel')
|
||||
</script>
|
||||
```
|
||||
|
||||
**Object syntax with validation:**
|
||||
```vue
|
||||
<script setup>
|
||||
// CORRECT: Runtime object for validation
|
||||
const emit = defineEmits({
|
||||
submit: (data) => {
|
||||
if (!data?.email) {
|
||||
console.warn('Missing email')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
cancel: null // No validation
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Adding Validation to Type-Based Emits
|
||||
|
||||
If you want TypeScript types AND runtime validation, define the validator separately:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface FormData {
|
||||
email: string
|
||||
message: string
|
||||
}
|
||||
|
||||
// Type-based declaration for TypeScript
|
||||
const emit = defineEmits<{
|
||||
submit: [data: FormData]
|
||||
}>()
|
||||
|
||||
// Separate validation function
|
||||
function emitSubmit(data: FormData) {
|
||||
if (!data.email.includes('@')) {
|
||||
console.warn('Invalid email format')
|
||||
return
|
||||
}
|
||||
emit('submit', data)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="emitSubmit(formData)">Submit</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Choosing Between Styles
|
||||
|
||||
| Style | Use When | Benefits |
|
||||
|-------|----------|----------|
|
||||
| Type-based | TypeScript project | Compile-time checking, IDE support |
|
||||
| Array | JavaScript, simple events | Simple, no types needed |
|
||||
| Object | Need runtime validation | Validates payloads at runtime |
|
||||
|
||||
**Recommendation:** In TypeScript projects, use type-based declaration. It provides the best developer experience with autocompletion and type checking.
|
||||
|
||||
## Same Rule Applies to defineProps
|
||||
|
||||
This restriction also applies to `defineProps`:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// ERROR: Cannot mix
|
||||
const props = defineProps<{ name: string }>({ name: String })
|
||||
|
||||
// CORRECT: Type-based only
|
||||
const props = defineProps<{ name: string }>()
|
||||
|
||||
// CORRECT: Runtime only
|
||||
const props = defineProps({ name: String })
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js SFC script setup - defineEmits](https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits)
|
||||
- [Vue.js TypeScript with Composition API](https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits)
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
title: defineModel Object Properties Must Be Replaced, Not Mutated
|
||||
impact: HIGH
|
||||
impactDescription: Mutating object properties via defineModel doesn't emit update events, breaking parent sync
|
||||
type: gotcha
|
||||
tags: [vue3, v-model, defineModel, objects, reactivity, two-way-binding]
|
||||
---
|
||||
|
||||
# defineModel Object Properties Must Be Replaced, Not Mutated
|
||||
|
||||
**Impact: HIGH** - When using `defineModel()` with objects or arrays, directly mutating nested properties like `model.value.prop = x` does NOT emit the `update:modelValue` event. The parent component never receives the change notification, causing silent sync failures.
|
||||
|
||||
This happens because Vue only detects when the `model.value` reference itself changes, not when properties of the object are mutated in place.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Never mutate object properties directly: `model.value.prop = x`
|
||||
- [ ] Always create a new object reference when updating: `model.value = {...model.value, prop: x}`
|
||||
- [ ] For arrays, use spread or slice: `model.value = [...model.value, newItem]`
|
||||
- [ ] Consider using structuredClone for deeply nested objects
|
||||
|
||||
**Incorrect - Mutation without event emission:**
|
||||
```vue
|
||||
<script setup>
|
||||
// Child component with object v-model
|
||||
const model = defineModel<{ name: string; age: number }>()
|
||||
|
||||
function updateName(newName: string) {
|
||||
// WRONG: This mutates the object in place
|
||||
// Parent receives NO update:modelValue event!
|
||||
model.value.name = newName
|
||||
}
|
||||
|
||||
function addToList() {
|
||||
// WRONG: Push mutates the array
|
||||
model.value.items.push('new item') // Parent not notified
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct - Replace object reference to trigger event:**
|
||||
```vue
|
||||
<script setup>
|
||||
const model = defineModel<{ name: string; age: number }>()
|
||||
|
||||
function updateName(newName: string) {
|
||||
// CORRECT: Create new object reference
|
||||
// This triggers update:modelValue event to parent
|
||||
model.value = {
|
||||
...model.value,
|
||||
name: newName
|
||||
}
|
||||
}
|
||||
|
||||
function addToList() {
|
||||
// CORRECT: Create new array reference
|
||||
model.value = {
|
||||
...model.value,
|
||||
items: [...model.value.items, 'new item']
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Deep Nesting Requires Full Path Replacement
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const model = defineModel<{
|
||||
user: {
|
||||
address: {
|
||||
city: string
|
||||
}
|
||||
}
|
||||
}>()
|
||||
|
||||
// WRONG: Deep mutation
|
||||
model.value.user.address.city = 'New York'
|
||||
|
||||
// CORRECT: Replace entire chain
|
||||
model.value = {
|
||||
...model.value,
|
||||
user: {
|
||||
...model.value.user,
|
||||
address: {
|
||||
...model.value.user.address,
|
||||
city: 'New York'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ALTERNATIVE: Use structuredClone for complex updates
|
||||
function updateCity(city: string) {
|
||||
const updated = structuredClone(model.value)
|
||||
updated.user.address.city = city
|
||||
model.value = updated // New reference triggers event
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Race Condition Warning with Spread Operator
|
||||
|
||||
When multiple updates occur rapidly, earlier changes can be lost:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const model = defineModel<{ a: string; b: string }>()
|
||||
|
||||
// CAUTION: Race condition if called in same tick
|
||||
function updateBothWrong() {
|
||||
model.value = { ...model.value, a: 'new-a' } // First update
|
||||
model.value = { ...model.value, b: 'new-b' } // May use stale model.value!
|
||||
}
|
||||
|
||||
// CORRECT: Batch updates into single assignment
|
||||
function updateBothCorrect() {
|
||||
model.value = {
|
||||
...model.value,
|
||||
a: 'new-a',
|
||||
b: 'new-b'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Alternative: VueUse's useVModel with Deep Option
|
||||
|
||||
For complex objects, consider VueUse:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useVModel } from '@vueuse/core'
|
||||
|
||||
const props = defineProps<{ modelValue: { name: string } }>()
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
|
||||
// Deep tracking with passive updates
|
||||
const model = useVModel(props, 'modelValue', emit, { deep: true, passive: true })
|
||||
|
||||
// Now direct mutations work
|
||||
model.value.name = 'New Name' // Properly syncs with parent
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component v-model](https://vuejs.org/guide/components/v-model.html)
|
||||
- [GitHub Discussion: defineModel with objects](https://github.com/orgs/vuejs/discussions/10538)
|
||||
- [SIMPL Engineering: Vue defineModel Pitfalls](https://engineering.simpl.de/post/vue_definemodel/)
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
title: Use nextTick() to Wait for DOM Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: DOM updates are batched and asynchronous - direct DOM access after state changes sees stale values
|
||||
type: capability
|
||||
tags: [vue3, dom, nextTick, reactivity, async]
|
||||
---
|
||||
|
||||
# Use nextTick() to Wait for DOM Updates
|
||||
|
||||
**Impact: MEDIUM** - Vue batches DOM updates asynchronously for performance. If you access the DOM immediately after changing reactive state, you'll see the old values. Use `nextTick()` to wait for the DOM to update.
|
||||
|
||||
When you modify reactive state, Vue doesn't update the DOM synchronously. Instead, it buffers changes and applies them in the next "tick" of the event loop. This is a performance optimization, but it can cause bugs when you need to read from or manipulate the DOM after state changes.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use `await nextTick()` when you need to access updated DOM elements after state changes
|
||||
- [ ] Use `nextTick()` when measuring DOM elements (heights, widths) after data changes
|
||||
- [ ] Use `nextTick()` when focusing inputs or scrolling after content updates
|
||||
- [ ] Consider if you really need DOM access - often you can work with reactive data instead
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
import { ref } from 'vue'
|
||||
|
||||
const message = ref('Hello')
|
||||
const messageEl = ref(null)
|
||||
|
||||
function updateMessage() {
|
||||
message.value = 'Updated!'
|
||||
|
||||
// WRONG: DOM still shows "Hello" at this point
|
||||
console.log(messageEl.value.textContent) // "Hello" - stale!
|
||||
|
||||
// WRONG: Scrolling/focusing may not work correctly
|
||||
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
import { ref, nextTick } from 'vue'
|
||||
|
||||
const message = ref('Hello')
|
||||
const messageEl = ref(null)
|
||||
|
||||
async function updateMessage() {
|
||||
message.value = 'Updated!'
|
||||
|
||||
// CORRECT: Wait for DOM to update
|
||||
await nextTick()
|
||||
|
||||
// Now the DOM is updated
|
||||
console.log(messageEl.value.textContent) // "Updated!"
|
||||
|
||||
// Scrolling and focusing now work correctly
|
||||
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
|
||||
}
|
||||
|
||||
// Alternative: callback syntax
|
||||
function updateWithCallback() {
|
||||
message.value = 'Updated!'
|
||||
|
||||
nextTick(() => {
|
||||
console.log(messageEl.value.textContent) // "Updated!"
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, nextTick } from 'vue'
|
||||
|
||||
const items = ref([])
|
||||
const listRef = ref(null)
|
||||
|
||||
async function addItem() {
|
||||
items.value.push({ id: Date.now(), text: 'New item' })
|
||||
|
||||
await nextTick()
|
||||
|
||||
// Now we can safely scroll to the new item
|
||||
listRef.value.lastElementChild?.scrollIntoView({ behavior: 'smooth' })
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Reactivity Fundamentals - DOM Update Timing](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#dom-update-timing)
|
||||
- [Vue.js nextTick API](https://vuejs.org/api/general.html#nexttick)
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
title: Dynamic Directive Arguments Have Syntax Constraints
|
||||
impact: MEDIUM
|
||||
impactDescription: Invalid dynamic arguments cause silent failures or browser compatibility issues
|
||||
type: capability
|
||||
tags: [vue3, template, directives, v-bind, v-on, dynamic-arguments]
|
||||
---
|
||||
|
||||
# Dynamic Directive Arguments Have Syntax Constraints
|
||||
|
||||
**Impact: MEDIUM** - Dynamic directive arguments (e.g., `:[attributeName]`, `@[eventName]`) have value and syntax constraints that can cause silent failures. In-DOM templates also have case sensitivity issues with browsers lowercasing attribute names.
|
||||
|
||||
Dynamic arguments allow runtime determination of which attribute or event to bind, but they have restrictions that differ from static arguments.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Ensure dynamic arguments evaluate to strings or `null`
|
||||
- [ ] Avoid spaces and quotes inside dynamic argument brackets
|
||||
- [ ] Use computed properties for complex dynamic argument expressions
|
||||
- [ ] In in-DOM templates, use lowercase attribute names or switch to SFCs
|
||||
- [ ] Use `null` to explicitly remove a binding
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- ERROR: Spaces and quotes not allowed in dynamic arguments -->
|
||||
<a :[' foo' + bar]="value">Link</a>
|
||||
<a :["data-" + name]="value">Link</a>
|
||||
|
||||
<!-- WARNING: Non-string values (except null) trigger warnings -->
|
||||
<a :[123]="value">Link</a>
|
||||
<a :[someObject]="value">Link</a>
|
||||
|
||||
<!-- BUG in in-DOM templates: Browsers lowercase attribute names -->
|
||||
<!-- This becomes :[someattr] which won't match someAttr -->
|
||||
<a :[someAttr]="url">Link</a>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// If component expects someAttr but browser lowercases to someattr
|
||||
// the binding silently fails
|
||||
const someAttr = 'href'
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- OK: Simple variable reference -->
|
||||
<a :[attributeName]="url">Link</a>
|
||||
|
||||
<!-- OK: Use computed property for complex expressions -->
|
||||
<a :[dynamicAttr]="value">Link</a>
|
||||
|
||||
<!-- OK: null removes the binding -->
|
||||
<button :[disabledAttr]="isDisabled">Submit</button>
|
||||
|
||||
<!-- OK: Dynamic event names -->
|
||||
<button @[eventName]="handler">Click</button>
|
||||
|
||||
<!-- OK: In SFCs, case is preserved -->
|
||||
<a :[someAttr]="url">Link</a>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
// Simple string variable
|
||||
const attributeName = ref('href')
|
||||
const url = ref('https://vuejs.org')
|
||||
|
||||
// Complex expression via computed property
|
||||
const prefix = ref('data')
|
||||
const name = ref('id')
|
||||
const dynamicAttr = computed(() => `${prefix.value}-${name.value}`)
|
||||
|
||||
// Conditional binding with null
|
||||
const isDisabled = ref(false)
|
||||
const disabledAttr = computed(() => isDisabled.value ? 'disabled' : null)
|
||||
|
||||
// Dynamic events
|
||||
const useTouch = ref(false)
|
||||
const eventName = computed(() => useTouch.value ? 'touchstart' : 'click')
|
||||
|
||||
function handler() {
|
||||
console.log('Event triggered')
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## In-DOM Template Workaround
|
||||
|
||||
When writing templates directly in HTML (not SFCs), use lowercase:
|
||||
|
||||
```html
|
||||
<!-- In-DOM template (index.html) -->
|
||||
<div id="app">
|
||||
<!-- Use lowercase to avoid browser issues -->
|
||||
<a :[attrname]="url">Link</a>
|
||||
</div>
|
||||
|
||||
<script type="module">
|
||||
import { createApp, ref } from 'vue'
|
||||
|
||||
createApp({
|
||||
setup() {
|
||||
// Match the lowercase used in template
|
||||
const attrname = ref('href')
|
||||
const url = ref('https://vuejs.org')
|
||||
return { attrname, url }
|
||||
}
|
||||
}).mount('#app')
|
||||
</script>
|
||||
```
|
||||
|
||||
## SFC vs In-DOM Templates
|
||||
|
||||
| Feature | SFC (.vue files) | In-DOM (HTML) |
|
||||
|---------|------------------|---------------|
|
||||
| Case sensitivity | Preserved | Lowercased by browser |
|
||||
| Dynamic arguments | Full support | Lowercase only |
|
||||
| Recommendation | Preferred | Use for progressive enhancement |
|
||||
|
||||
## Valid Dynamic Argument Values
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// String values - OK
|
||||
const attr1 = 'href'
|
||||
const attr2 = 'data-custom'
|
||||
|
||||
// null - OK (removes binding)
|
||||
const attr3 = null
|
||||
|
||||
// undefined - OK (removes binding)
|
||||
const attr4 = undefined
|
||||
|
||||
// Numbers, objects, arrays - WARNING
|
||||
const attr5 = 123 // Warning: should be string
|
||||
const attr6 = { foo: 1 } // Warning: should be string
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Template Syntax - Dynamic Arguments](https://vuejs.org/guide/essentials/template-syntax.html#dynamic-arguments)
|
||||
- [Vue.js Template Syntax - Dynamic Argument Value Constraints](https://vuejs.org/guide/essentials/template-syntax.html#dynamic-argument-value-constraints)
|
||||
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: Use import.meta.glob for Dynamic Component Registration in Vite
|
||||
impact: MEDIUM
|
||||
impactDescription: require.context from Webpack doesn't work in Vite projects
|
||||
type: gotcha
|
||||
tags: [vue3, component-registration, vite, dynamic-import, migration, webpack]
|
||||
---
|
||||
|
||||
# Use import.meta.glob for Dynamic Component Registration in Vite
|
||||
|
||||
**Impact: MEDIUM** - When migrating from Webpack to Vite or starting a new Vite project, the `require.context` pattern for dynamically registering components won't work. Vite uses `import.meta.glob` instead. Using the wrong approach will cause build errors or runtime failures.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Replace `require.context` with `import.meta.glob` in Vite projects
|
||||
- [ ] Update component registration patterns when migrating from Vue CLI to Vite
|
||||
- [ ] Use `{ eager: true }` for synchronous loading when needed
|
||||
- [ ] Handle async components appropriately with `defineAsyncComponent`
|
||||
|
||||
**Incorrect (Webpack pattern - doesn't work in Vite):**
|
||||
```javascript
|
||||
// main.js - WRONG for Vite
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// This Webpack-specific API doesn't exist in Vite
|
||||
const requireComponent = require.context(
|
||||
'./components/base',
|
||||
false,
|
||||
/Base[A-Z]\w+\.vue$/
|
||||
)
|
||||
|
||||
requireComponent.keys().forEach(fileName => {
|
||||
const componentConfig = requireComponent(fileName)
|
||||
const componentName = fileName
|
||||
.split('/')
|
||||
.pop()
|
||||
.replace(/\.\w+$/, '')
|
||||
|
||||
app.component(componentName, componentConfig.default || componentConfig)
|
||||
})
|
||||
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
**Correct (Vite pattern):**
|
||||
```javascript
|
||||
// main.js - Correct for Vite
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// Vite's glob import - eager loading for synchronous registration
|
||||
const modules = import.meta.glob('./components/base/Base*.vue', { eager: true })
|
||||
|
||||
for (const path in modules) {
|
||||
// Extract component name from path: './components/base/BaseButton.vue' -> 'BaseButton'
|
||||
const componentName = path.split('/').pop().replace('.vue', '')
|
||||
app.component(componentName, modules[path].default)
|
||||
}
|
||||
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## Lazy Loading with Async Components
|
||||
|
||||
```javascript
|
||||
// main.js - Lazy loading variant
|
||||
import { createApp, defineAsyncComponent } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// Without { eager: true }, returns functions that return Promises
|
||||
const modules = import.meta.glob('./components/base/Base*.vue')
|
||||
|
||||
for (const path in modules) {
|
||||
const componentName = path.split('/').pop().replace('.vue', '')
|
||||
// Wrap in defineAsyncComponent for lazy loading
|
||||
app.component(componentName, defineAsyncComponent(modules[path]))
|
||||
}
|
||||
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## Glob Pattern Examples
|
||||
|
||||
```javascript
|
||||
// All .vue files in a directory (not recursive)
|
||||
import.meta.glob('./components/*.vue', { eager: true })
|
||||
|
||||
// All .vue files recursively
|
||||
import.meta.glob('./components/**/*.vue', { eager: true })
|
||||
|
||||
// Specific naming pattern
|
||||
import.meta.glob('./components/Base*.vue', { eager: true })
|
||||
|
||||
// Multiple patterns
|
||||
import.meta.glob([
|
||||
'./components/Base*.vue',
|
||||
'./components/App*.vue'
|
||||
], { eager: true })
|
||||
|
||||
// Exclude patterns
|
||||
import.meta.glob('./components/**/*.vue', {
|
||||
eager: true,
|
||||
ignore: ['**/*.test.vue', '**/*.spec.vue']
|
||||
})
|
||||
```
|
||||
|
||||
## TypeScript Support
|
||||
|
||||
```typescript
|
||||
// main.ts - with proper typing
|
||||
import { createApp, Component } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
const modules = import.meta.glob<{ default: Component }>(
|
||||
'./components/base/Base*.vue',
|
||||
{ eager: true }
|
||||
)
|
||||
|
||||
for (const path in modules) {
|
||||
const componentName = path.split('/').pop()!.replace('.vue', '')
|
||||
app.component(componentName, modules[path].default)
|
||||
}
|
||||
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## Migration Checklist (Webpack to Vite)
|
||||
|
||||
| Webpack | Vite |
|
||||
|---------|------|
|
||||
| `require.context(dir, recursive, regex)` | `import.meta.glob(pattern, options)` |
|
||||
| Synchronous by default | Use `{ eager: true }` for sync |
|
||||
| `.keys()` returns array | Returns object with paths as keys |
|
||||
| Returns module directly | Access via `.default` for ES modules |
|
||||
|
||||
## Reference
|
||||
- [Vite - Glob Import](https://vitejs.dev/guide/features.html#glob-import)
|
||||
- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html)
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
title: Event Modifier Order Matters
|
||||
impact: MEDIUM
|
||||
impactDescription: Modifier order affects event handling behavior - wrong order causes unexpected propagation or prevention
|
||||
type: gotcha
|
||||
tags: [vue3, events, modifiers, v-on, click, form]
|
||||
---
|
||||
|
||||
# Event Modifier Order Matters
|
||||
|
||||
**Impact: MEDIUM** - When chaining event modifiers, the order determines behavior because Vue generates code in the same sequence. Using `.prevent.self` vs `.self.prevent` produces different results that can cause subtle bugs in event handling.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Always consider modifier order when chaining multiple modifiers
|
||||
- [ ] Use `.prevent.self` to prevent default on element AND children
|
||||
- [ ] Use `.self.prevent` to prevent default ONLY on the element itself
|
||||
- [ ] Test event behavior on both the element and its children
|
||||
|
||||
**Incorrect:**
|
||||
```html
|
||||
<!-- WRONG: Unintended behavior - prevents clicks on children too -->
|
||||
<template>
|
||||
<div @click.prevent.self="handleClick">
|
||||
<button>Child Button</button> <!-- Default also prevented here! -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Assuming order doesn't matter -->
|
||||
<template>
|
||||
<!-- Developer expects only self clicks to be handled -->
|
||||
<!-- But .prevent runs first, affecting all clicks -->
|
||||
<a href="/page" @click.prevent.self="navigate">
|
||||
<span>Click me</span>
|
||||
</a>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- CORRECT: Only prevent default on the element itself -->
|
||||
<template>
|
||||
<div @click.self.prevent="handleClick">
|
||||
<button>Child Button</button> <!-- Default NOT prevented here -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Prevent default on element and children -->
|
||||
<template>
|
||||
<form @submit.prevent.self="onSubmit">
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Explicit intent with separate handlers when needed -->
|
||||
<template>
|
||||
<div @click.self="handleSelfClick">
|
||||
<button @click.prevent="handleChildClick">
|
||||
Child with prevented default
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## How Modifier Order Works
|
||||
|
||||
```javascript
|
||||
// Vue compiles modifiers in order, so:
|
||||
|
||||
// @click.prevent.self compiles to:
|
||||
// event.preventDefault()
|
||||
// if (event.target !== event.currentTarget) return
|
||||
// handler()
|
||||
|
||||
// @click.self.prevent compiles to:
|
||||
// if (event.target !== event.currentTarget) return
|
||||
// event.preventDefault()
|
||||
// handler()
|
||||
```
|
||||
|
||||
## Common Modifier Combinations
|
||||
|
||||
```html
|
||||
<!-- Stop propagation AND prevent default -->
|
||||
<a @click.stop.prevent="handleClick">Link</a>
|
||||
|
||||
<!-- Capture mode with once -->
|
||||
<div @click.capture.once="handleOnce">...</div>
|
||||
|
||||
<!-- Only exact modifier key combination -->
|
||||
<button @click.ctrl.exact="onCtrlClick">Ctrl+Click Only</button>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Event Handling - Event Modifiers](https://vuejs.org/guide/essentials/event-handling.html#event-modifiers)
|
||||
@@ -0,0 +1,155 @@
|
||||
---
|
||||
title: Use .exact Modifier for Precise Keyboard/Mouse Shortcuts
|
||||
impact: MEDIUM
|
||||
impactDescription: Without .exact, shortcuts fire even when additional modifier keys are pressed, causing unintended behavior
|
||||
type: best-practice
|
||||
tags: [vue3, events, keyboard, modifiers, shortcuts, accessibility]
|
||||
---
|
||||
|
||||
# Use .exact Modifier for Precise Keyboard/Mouse Shortcuts
|
||||
|
||||
**Impact: MEDIUM** - By default, Vue's modifier key handlers (`.ctrl`, `.alt`, `.shift`, `.meta`) fire even when other modifier keys are also pressed. Use `.exact` to require that ONLY the specified modifiers are pressed, preventing accidental triggering of shortcuts.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use `.exact` when you need precise modifier combinations
|
||||
- [ ] Without `.exact`: `@click.ctrl` fires for Ctrl+Click AND Ctrl+Shift+Click
|
||||
- [ ] With `.exact`: `@click.ctrl.exact` fires ONLY for Ctrl+Click
|
||||
- [ ] Use `@click.exact` for plain clicks with no modifiers
|
||||
|
||||
**Incorrect:**
|
||||
```html
|
||||
<!-- WRONG: Fires even with additional modifiers -->
|
||||
<template>
|
||||
<button @click.ctrl="copyItem">Copy</button>
|
||||
<!-- Also fires on Ctrl+Shift+Click, Ctrl+Alt+Click, etc. -->
|
||||
|
||||
<button @click.ctrl.shift="copyAll">Copy All</button>
|
||||
<!-- User expects Ctrl+Shift, but also fires on Ctrl+Shift+Alt -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Conflicting shortcuts without .exact -->
|
||||
<template>
|
||||
<div>
|
||||
<button @click.ctrl="copy">Copy (Ctrl+Click)</button>
|
||||
<button @click.ctrl.shift="copyAll">Copy All (Ctrl+Shift+Click)</button>
|
||||
<!-- Both fire when user does Ctrl+Shift+Click! -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- CORRECT: Precise modifier matching with .exact -->
|
||||
<template>
|
||||
<button @click.ctrl.exact="copyItem">Copy (Ctrl only)</button>
|
||||
<!-- Only fires on Ctrl+Click, not Ctrl+Shift+Click -->
|
||||
|
||||
<button @click.ctrl.shift.exact="copyAll">Copy All (Ctrl+Shift only)</button>
|
||||
<!-- Only fires on Ctrl+Shift+Click, not Ctrl+Shift+Alt+Click -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Plain click without any modifiers -->
|
||||
<template>
|
||||
<button @click.exact="selectItem">Select</button>
|
||||
<!-- Only fires when NO modifier keys are pressed -->
|
||||
<!-- Ctrl+Click, Shift+Click, etc. will NOT trigger this -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Non-conflicting shortcuts -->
|
||||
<template>
|
||||
<div class="editor">
|
||||
<div
|
||||
@click.exact="selectItem"
|
||||
@click.ctrl.exact="addToSelection"
|
||||
@click.shift.exact="extendSelection"
|
||||
@click.ctrl.shift.exact="selectRange"
|
||||
>
|
||||
Click, Ctrl+Click, Shift+Click, or Ctrl+Shift+Click
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Behavior Comparison
|
||||
|
||||
```javascript
|
||||
// WITHOUT .exact
|
||||
@click.ctrl="handler"
|
||||
// Fires when: Ctrl+Click, Ctrl+Shift+Click, Ctrl+Alt+Click, Ctrl+Shift+Alt+Click
|
||||
// Does NOT fire: Click (without Ctrl)
|
||||
|
||||
// WITH .exact
|
||||
@click.ctrl.exact="handler"
|
||||
// Fires when: ONLY Ctrl+Click
|
||||
// Does NOT fire: Ctrl+Shift+Click, Ctrl+Alt+Click, Click
|
||||
|
||||
// ONLY .exact (no other modifiers)
|
||||
@click.exact="handler"
|
||||
// Fires when: Plain click with NO modifiers
|
||||
// Does NOT fire: Ctrl+Click, Shift+Click, Alt+Click
|
||||
```
|
||||
|
||||
## Practical Example: File Browser Selection
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<ul class="file-list">
|
||||
<li
|
||||
v-for="file in files"
|
||||
:key="file.id"
|
||||
@click.exact="selectSingle(file)"
|
||||
@click.ctrl.exact="toggleSelection(file)"
|
||||
@click.shift.exact="selectRange(file)"
|
||||
@click.ctrl.shift.exact="addRangeToSelection(file)"
|
||||
:class="{ selected: isSelected(file) }"
|
||||
>
|
||||
{{ file.name }}
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// Each click type has distinct, non-overlapping behavior
|
||||
function selectSingle(file) {
|
||||
// Clear selection and select only this file
|
||||
}
|
||||
|
||||
function toggleSelection(file) {
|
||||
// Add or remove this file from current selection
|
||||
}
|
||||
|
||||
function selectRange(file) {
|
||||
// Select all files from last selected to this one
|
||||
}
|
||||
|
||||
function addRangeToSelection(file) {
|
||||
// Add range to existing selection
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Keyboard Shortcuts with .exact
|
||||
|
||||
```html
|
||||
<template>
|
||||
<div
|
||||
tabindex="0"
|
||||
@keydown.ctrl.s.exact.prevent="save"
|
||||
@keydown.ctrl.shift.s.exact.prevent="saveAs"
|
||||
@keydown.ctrl.z.exact.prevent="undo"
|
||||
@keydown.ctrl.shift.z.exact.prevent="redo"
|
||||
>
|
||||
<!-- Each shortcut is precisely defined -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Event Handling - .exact Modifier](https://vuejs.org/guide/essentials/event-handling.html#exact-modifier)
|
||||
@@ -0,0 +1,159 @@
|
||||
# Fallthrough Attributes Overwrite Explicit Attributes in Vue 3
|
||||
|
||||
## Rule
|
||||
|
||||
In Vue 3, fallthrough attributes overwrite explicitly set attributes on the root element (except `class` and `style` which are merged). This is a breaking change from Vue 2. To preserve explicit attribute values, use `inheritAttrs: false` and manually bind `$attrs` before the explicit attribute.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
- Silent behavior change from Vue 2 to Vue 3
|
||||
- Can cause unexpected attribute values in migrated codebases
|
||||
- Only `class` and `style` merge intelligently; other attributes are overwritten
|
||||
- Affects component composition patterns and wrapper components
|
||||
|
||||
## Bad Code
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<Child msg="Passed from Parent" />
|
||||
</template>
|
||||
|
||||
<!-- Child.vue - UNEXPECTED BEHAVIOR -->
|
||||
<template>
|
||||
<GrandChild msg="Set in Child" />
|
||||
</template>
|
||||
|
||||
<!--
|
||||
Vue 3 Result: GrandChild receives msg="Passed from Parent"
|
||||
The fallthrough attribute OVERWRITES the explicit one!
|
||||
|
||||
Vue 2 Result: GrandChild receives msg="Set in Child"
|
||||
The explicit attribute took precedence
|
||||
-->
|
||||
```
|
||||
|
||||
### Another common case with data attributes
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<Button data-testid="parent-button" />
|
||||
</template>
|
||||
|
||||
<!-- Button.vue - WRONG: explicit data-testid is overwritten -->
|
||||
<template>
|
||||
<button data-testid="submit-btn">Submit</button>
|
||||
</template>
|
||||
|
||||
<!-- Result: <button data-testid="parent-button">Submit</button> -->
|
||||
<!-- The component's intended test ID is lost! -->
|
||||
```
|
||||
|
||||
## Good Code
|
||||
|
||||
### Option 1: Control attribute order with inheritAttrs: false
|
||||
|
||||
```vue
|
||||
<!-- Child.vue - CORRECT: Control attribute precedence -->
|
||||
<script setup>
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- v-bind="$attrs" FIRST, then explicit attribute -->
|
||||
<GrandChild v-bind="$attrs" msg="Set in Child" />
|
||||
</template>
|
||||
|
||||
<!--
|
||||
Result: GrandChild receives msg="Set in Child"
|
||||
Explicit attribute overrides fallthrough because it comes last
|
||||
-->
|
||||
```
|
||||
|
||||
### Option 2: Exclude specific attrs from fallthrough
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { computed, useAttrs } from 'vue'
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
// Filter out attributes you want to control explicitly
|
||||
const filteredAttrs = computed(() => {
|
||||
const { msg, ...rest } = attrs
|
||||
return rest
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<GrandChild v-bind="filteredAttrs" msg="Set in Child" />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 3: For wrapper components, declare as prop
|
||||
|
||||
```vue
|
||||
<!-- Button.vue - BEST: Declare attributes you need to control -->
|
||||
<script setup>
|
||||
const props = defineProps({
|
||||
dataTestid: {
|
||||
type: String,
|
||||
default: 'submit-btn'
|
||||
}
|
||||
})
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button :data-testid="dataTestid" v-bind="$attrs">
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Class and Style Are Special
|
||||
|
||||
Unlike other attributes, `class` and `style` merge rather than overwrite:
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<Button class="large" style="color: red" />
|
||||
</template>
|
||||
|
||||
<!-- Button.vue -->
|
||||
<template>
|
||||
<button class="btn" style="padding: 10px">Submit</button>
|
||||
</template>
|
||||
|
||||
<!--
|
||||
Result: <button class="btn large" style="padding: 10px; color: red">
|
||||
Both classes and styles are MERGED, not overwritten
|
||||
-->
|
||||
```
|
||||
|
||||
## Vue 2 to Vue 3 Migration Checklist
|
||||
|
||||
When migrating components that rely on attribute precedence:
|
||||
|
||||
1. Identify components that set explicit attributes on root elements
|
||||
2. Check if parent components pass the same attributes
|
||||
3. If explicit values should take precedence:
|
||||
- Add `inheritAttrs: false`
|
||||
- Use `v-bind="$attrs"` before explicit attributes
|
||||
|
||||
## References
|
||||
|
||||
- [Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
|
||||
- [Vue 3 Migration Guide - Attribute Coercion Behavior](https://v3-migration.vuejs.org/breaking-changes/)
|
||||
- [Vue Fallthrough Attributes behaviour changes from Vue 2 to Vue 3](https://lukes.tips/posts/vue-3-fallthough-attributes-changes/)
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
title: In-DOM Template Parsing Caveats
|
||||
impact: HIGH
|
||||
impactDescription: Browser HTML parsing before Vue compilation causes case sensitivity, self-closing tag, and element nesting issues
|
||||
type: gotcha
|
||||
tags: [vue3, templates, in-dom, html-parsing, kebab-case, self-closing-tags]
|
||||
---
|
||||
|
||||
# In-DOM Template Parsing Caveats
|
||||
|
||||
**Impact: HIGH** - When writing Vue templates directly in the DOM (not in `.vue` files), the browser's native HTML parser processes the template BEFORE Vue sees it. This causes three critical issues: case sensitivity problems, self-closing tag failures, and element placement restrictions.
|
||||
|
||||
These issues do NOT apply to Single-File Components (SFCs) or string templates where Vue's compiler handles parsing directly.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Use kebab-case for component names in in-DOM templates
|
||||
- [ ] Use kebab-case for prop names in in-DOM templates
|
||||
- [ ] Use explicit closing tags (not self-closing) in in-DOM templates
|
||||
- [ ] Use `is="vue:component-name"` for components inside restricted elements
|
||||
- [ ] Prefer SFCs to avoid all in-DOM parsing issues
|
||||
|
||||
## Issue 1: Case Insensitivity
|
||||
|
||||
HTML is case-insensitive. The browser lowercases everything before Vue sees it.
|
||||
|
||||
**Incorrect (in-DOM template):**
|
||||
```html
|
||||
<!-- Browser converts to: <blogpost posttitle="hello"> -->
|
||||
<BlogPost postTitle="hello" @updatePost="onUpdate"></BlogPost>
|
||||
```
|
||||
|
||||
**Correct (in-DOM template):**
|
||||
```html
|
||||
<!-- Use kebab-case for everything -->
|
||||
<blog-post post-title="hello" @update-post="onUpdate"></blog-post>
|
||||
```
|
||||
|
||||
**In SFCs, PascalCase works fine:**
|
||||
```vue
|
||||
<!-- BlogPost.vue - PascalCase recommended -->
|
||||
<template>
|
||||
<BlogPost postTitle="hello" @updatePost="onUpdate" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Issue 2: Self-Closing Tags Fail
|
||||
|
||||
HTML only allows self-closing syntax for void elements (`<input>`, `<img>`, etc.). For all others, the browser expects closing tags.
|
||||
|
||||
**Incorrect (in-DOM template):**
|
||||
```html
|
||||
<!-- Browser thinks the tag never closed, breaks nesting -->
|
||||
<my-component />
|
||||
<another-component />
|
||||
```
|
||||
|
||||
**Correct (in-DOM template):**
|
||||
```html
|
||||
<!-- Explicit closing tags required -->
|
||||
<my-component></my-component>
|
||||
<another-component></another-component>
|
||||
```
|
||||
|
||||
**In SFCs, self-closing works fine:**
|
||||
```vue
|
||||
<template>
|
||||
<MyComponent />
|
||||
<AnotherComponent />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Issue 3: Element Placement Restrictions
|
||||
|
||||
Some HTML elements have strict rules about valid children. Invalid elements are hoisted out by the browser before Vue sees the template.
|
||||
|
||||
**Restricted parent elements:**
|
||||
- `<ul>`, `<ol>` - only allow `<li>`
|
||||
- `<table>` - only allows `<thead>`, `<tbody>`, `<tfoot>`, `<tr>`, `<caption>`, `<colgroup>`
|
||||
- `<tr>` - only allows `<td>`, `<th>`
|
||||
- `<select>` - only allows `<option>`, `<optgroup>`
|
||||
|
||||
**Incorrect (in-DOM template):**
|
||||
```html
|
||||
<!-- Browser hoists blog-post-row outside the table -->
|
||||
<table>
|
||||
<blog-post-row v-for="post in posts" :post="post"></blog-post-row>
|
||||
</table>
|
||||
|
||||
<!-- Renders as: -->
|
||||
<blog-post-row></blog-post-row>
|
||||
<blog-post-row></blog-post-row>
|
||||
<table></table>
|
||||
```
|
||||
|
||||
**Correct (in-DOM template):**
|
||||
```html
|
||||
<!-- Use is="vue:component-name" on a valid native element -->
|
||||
<table>
|
||||
<tr is="vue:blog-post-row" v-for="post in posts" :key="post.id" :post="post"></tr>
|
||||
</table>
|
||||
```
|
||||
|
||||
```html
|
||||
<ul>
|
||||
<li is="vue:todo-item" v-for="todo in todos" :key="todo.id" :todo="todo"></li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
**Important:** The `vue:` prefix is required! Without it, `is` is treated as a native customized built-in element attribute.
|
||||
|
||||
```html
|
||||
<!-- WRONG: Missing vue: prefix -->
|
||||
<tr is="blog-post-row"></tr>
|
||||
|
||||
<!-- CORRECT: With vue: prefix -->
|
||||
<tr is="vue:blog-post-row"></tr>
|
||||
```
|
||||
|
||||
## When Do These Apply?
|
||||
|
||||
| Template Type | Affected? | Example |
|
||||
|---------------|-----------|---------|
|
||||
| Single-File Component (`.vue`) | No | `<template>` section |
|
||||
| String template | No | `template: '<div>...</div>'` |
|
||||
| In-DOM template | **Yes** | `<div id="app">...</div>` |
|
||||
| `<script type="text/x-template">` | **Yes** | Browser parses the script content |
|
||||
|
||||
## Best Practice: Use SFCs
|
||||
|
||||
The simplest solution is to use Single-File Components (`.vue` files) which completely avoid in-DOM parsing issues:
|
||||
|
||||
```vue
|
||||
<!-- MyComponent.vue - All issues avoided -->
|
||||
<script setup>
|
||||
import BlogPost from './BlogPost.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BlogPost postTitle="hello" @updatePost="onUpdate" />
|
||||
|
||||
<table>
|
||||
<BlogPostRow v-for="post in posts" :key="post.id" :post="post" />
|
||||
</table>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js - In-DOM Template Parsing Caveats](https://vuejs.org/guide/essentials/component-basics.html#in-dom-template-parsing-caveats)
|
||||
@@ -0,0 +1,230 @@
|
||||
# Use inheritAttrs: false for Wrapper Components
|
||||
|
||||
## Rule
|
||||
|
||||
When building wrapper components where attributes should be applied to an inner element instead of the root element, always set `inheritAttrs: false` and explicitly bind `$attrs` to the target element.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
- By default, Vue applies all non-prop attributes to the root element
|
||||
- Wrapper components often have a non-semantic root (div wrapper, label wrapper)
|
||||
- Attributes like `id`, `aria-*`, `data-*`, and event listeners should target the functional element
|
||||
- Without `inheritAttrs: false`, accessibility and functionality can break
|
||||
|
||||
## Bad Code
|
||||
|
||||
```vue
|
||||
<!-- BaseInput.vue - WRONG: attrs go to wrapper div, not input -->
|
||||
<template>
|
||||
<div class="input-wrapper">
|
||||
<label>{{ label }}</label>
|
||||
<input type="text" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineProps(['label'])
|
||||
</script>
|
||||
|
||||
<!-- Parent usage -->
|
||||
<BaseInput
|
||||
id="email"
|
||||
placeholder="Enter email"
|
||||
aria-describedby="email-help"
|
||||
@focus="handleFocus"
|
||||
/>
|
||||
|
||||
<!--
|
||||
RESULT: All attrs go to the wrapper div!
|
||||
<div class="input-wrapper" id="email" placeholder="Enter email" ...>
|
||||
<label>...</label>
|
||||
<input type="text" /> <!-- No id, placeholder, or aria! -->
|
||||
</div>
|
||||
-->
|
||||
```
|
||||
|
||||
## Good Code
|
||||
|
||||
```vue
|
||||
<!-- BaseInput.vue - CORRECT: attrs bound to input element -->
|
||||
<script setup>
|
||||
defineProps(['label'])
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="input-wrapper">
|
||||
<label>{{ label }}</label>
|
||||
<input type="text" v-bind="$attrs" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Parent usage -->
|
||||
<BaseInput
|
||||
id="email"
|
||||
placeholder="Enter email"
|
||||
aria-describedby="email-help"
|
||||
@focus="handleFocus"
|
||||
/>
|
||||
|
||||
<!--
|
||||
RESULT: Attrs correctly applied to input
|
||||
<div class="input-wrapper">
|
||||
<label>...</label>
|
||||
<input type="text" id="email" placeholder="Enter email"
|
||||
aria-describedby="email-help" />
|
||||
</div>
|
||||
-->
|
||||
```
|
||||
|
||||
## Setting inheritAttrs in Different Syntaxes
|
||||
|
||||
### Script Setup (Vue 3.3+)
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Script Setup (Before Vue 3.3)
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
inheritAttrs: false
|
||||
}
|
||||
</script>
|
||||
|
||||
<script setup>
|
||||
// Your setup code here
|
||||
</script>
|
||||
```
|
||||
|
||||
### Options API
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
inheritAttrs: false,
|
||||
// other options...
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Common Wrapper Component Patterns
|
||||
|
||||
### Form Input Wrapper
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useAttrs, computed } from 'vue'
|
||||
|
||||
defineProps({
|
||||
label: String,
|
||||
error: String
|
||||
})
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
|
||||
const attrs = useAttrs()
|
||||
|
||||
// Separate class/style for wrapper vs input
|
||||
const inputAttrs = computed(() => {
|
||||
const { class: _, style: __, ...rest } = attrs
|
||||
return rest
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="form-field" :class="{ 'has-error': error }">
|
||||
<label v-if="label">{{ label }}</label>
|
||||
<input v-bind="inputAttrs" />
|
||||
<span v-if="error" class="error">{{ error }}</span>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Button with Icon Wrapper
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
defineProps({
|
||||
icon: String,
|
||||
iconPosition: {
|
||||
type: String,
|
||||
default: 'left'
|
||||
}
|
||||
})
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button class="icon-button" v-bind="$attrs">
|
||||
<span v-if="icon && iconPosition === 'left'" class="icon">{{ icon }}</span>
|
||||
<slot />
|
||||
<span v-if="icon && iconPosition === 'right'" class="icon">{{ icon }}</span>
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Link Wrapper Component
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
defineProps({
|
||||
to: String,
|
||||
external: Boolean
|
||||
})
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a
|
||||
v-if="external"
|
||||
:href="to"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
v-bind="$attrs"
|
||||
>
|
||||
<slot />
|
||||
</a>
|
||||
<router-link v-else :to="to" v-bind="$attrs">
|
||||
<slot />
|
||||
</router-link>
|
||||
</template>
|
||||
```
|
||||
|
||||
## When NOT to Use inheritAttrs: false
|
||||
|
||||
- Simple components with a single semantic root element
|
||||
- Components where the root element should receive all attributes
|
||||
- Components that don't wrap other functional elements
|
||||
|
||||
```vue
|
||||
<!-- SimpleCard.vue - No need for inheritAttrs: false -->
|
||||
<template>
|
||||
<article class="card">
|
||||
<slot />
|
||||
</article>
|
||||
</template>
|
||||
<!-- Passing class, id, or data-* to the root article is fine -->
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [Fallthrough Attributes - Disabling Attribute Inheritance](https://vuejs.org/guide/components/attrs.html#disabling-attribute-inheritance)
|
||||
- [Build Advanced Components in Vue 3 using $attrs](https://www.thisdot.co/blog/build-advanced-components-in-vue-3-using-usdattrs)
|
||||
@@ -0,0 +1,222 @@
|
||||
---
|
||||
title: KeepAlive with Nested Routes Double Mount Issue
|
||||
impact: HIGH
|
||||
impactDescription: Using KeepAlive with nested Vue Router routes can cause child components to mount twice
|
||||
type: gotcha
|
||||
tags: [vue3, keepalive, vue-router, nested-routes, double-mount, bug]
|
||||
---
|
||||
|
||||
# KeepAlive with Nested Routes Double Mount Issue
|
||||
|
||||
**Impact: HIGH** - When using `<KeepAlive>` with nested Vue Router routes, child route components may mount twice. This is a known issue that can cause duplicate API calls, broken state, and confusing behavior.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Test nested routes thoroughly when using KeepAlive
|
||||
- [ ] Avoid mixing KeepAlive with deeply nested route structures
|
||||
- [ ] Use workarounds if double mount is observed
|
||||
- [ ] Consider alternative caching strategies for nested routes
|
||||
|
||||
## The Problem
|
||||
|
||||
```vue
|
||||
<!-- App.vue -->
|
||||
<template>
|
||||
<router-view v-slot="{ Component }">
|
||||
<KeepAlive>
|
||||
<component :is="Component" />
|
||||
</KeepAlive>
|
||||
</router-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// router.js
|
||||
const routes = [
|
||||
{
|
||||
path: '/parent',
|
||||
component: Parent,
|
||||
children: [
|
||||
{
|
||||
path: 'child',
|
||||
component: Child // This may mount TWICE!
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Symptoms:**
|
||||
- `onMounted` called twice in child component
|
||||
- Duplicate API requests
|
||||
- State initialization runs twice
|
||||
- Console logs appear doubled
|
||||
|
||||
## Diagnosis
|
||||
|
||||
Add logging to confirm the issue:
|
||||
|
||||
```vue
|
||||
<!-- Child.vue -->
|
||||
<script setup>
|
||||
import { onMounted, onActivated } from 'vue'
|
||||
|
||||
let mountCount = 0
|
||||
|
||||
onMounted(() => {
|
||||
mountCount++
|
||||
console.log('Child mounted - count:', mountCount)
|
||||
// If you see "count: 2", you have the double mount issue
|
||||
})
|
||||
|
||||
onActivated(() => {
|
||||
console.log('Child activated')
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Workarounds
|
||||
|
||||
### Option 1: Use `useActivatedRoute` Pattern
|
||||
|
||||
Don't use `useRoute()` directly with KeepAlive:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onActivated } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
// Problem: useRoute() can cause issues with KeepAlive
|
||||
// const route = useRoute()
|
||||
|
||||
// Solution: Get route info in onActivated
|
||||
const routeParams = ref({})
|
||||
|
||||
onActivated(() => {
|
||||
const route = useRoute()
|
||||
routeParams.value = { ...route.params }
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Option 2: Avoid KeepAlive for Nested Route Parents
|
||||
|
||||
Only cache leaf routes, not parent layouts:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
// Only cache specific leaf routes
|
||||
const cachedRoutes = computed(() => {
|
||||
// Don't cache parent routes that have children
|
||||
return ['UserProfile', 'UserSettings'] // Only leaf components
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<router-view v-slot="{ Component, route: currentRoute }">
|
||||
<KeepAlive :include="cachedRoutes">
|
||||
<component :is="Component" :key="currentRoute.fullPath" />
|
||||
</KeepAlive>
|
||||
</router-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 3: Guard Against Double Initialization
|
||||
|
||||
Protect your component from double mount effects:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const isInitialized = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
if (isInitialized.value) {
|
||||
console.warn('Double mount detected, skipping initialization')
|
||||
return
|
||||
}
|
||||
isInitialized.value = true
|
||||
|
||||
// Safe to initialize
|
||||
fetchData()
|
||||
setupEventListeners()
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Option 4: Use Route-Level Cache Control
|
||||
|
||||
```vue
|
||||
<!-- App.vue -->
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
// Define which routes should be cached in route meta
|
||||
const shouldCache = computed(() => {
|
||||
return route.meta.keepAlive !== false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<router-view v-slot="{ Component }">
|
||||
<KeepAlive v-if="shouldCache">
|
||||
<component :is="Component" />
|
||||
</KeepAlive>
|
||||
<component v-else :is="Component" />
|
||||
</router-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// router.js
|
||||
const routes = [
|
||||
{
|
||||
path: '/parent',
|
||||
component: Parent,
|
||||
meta: { keepAlive: false }, // Don't cache parent routes
|
||||
children: [
|
||||
{
|
||||
path: 'child',
|
||||
component: Child,
|
||||
meta: { keepAlive: true } // Cache leaf routes
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Option 5: Flatten Route Structure
|
||||
|
||||
Avoid nesting if possible:
|
||||
|
||||
```javascript
|
||||
// Instead of nested routes
|
||||
const routes = [
|
||||
// Flat structure avoids the issue
|
||||
{ path: '/users', component: UserList },
|
||||
{ path: '/users/:id', component: UserDetail },
|
||||
{ path: '/users/:id/settings', component: UserSettings }
|
||||
]
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
1. **Known Vue Router issue** - Double mount with KeepAlive + nested routes
|
||||
2. **Watch for symptoms** - Duplicate API calls, doubled logs
|
||||
3. **Avoid caching parent routes** - Only cache leaf components
|
||||
4. **Add initialization guards** - Protect against double execution
|
||||
5. **Test thoroughly** - This issue may not appear immediately
|
||||
|
||||
## Reference
|
||||
- [Vue Router Issue #626: keep-alive in nested route mounted twice](https://github.com/vuejs/router/issues/626)
|
||||
- [GitHub: vue3-keep-alive-component workaround](https://github.com/emiyalee1005/vue3-keep-alive-component)
|
||||
- [Vue.js KeepAlive Documentation](https://vuejs.org/guide/built-ins/keep-alive.html)
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
title: KeepAlive with Transition Memory Leak
|
||||
impact: MEDIUM
|
||||
impactDescription: Combining KeepAlive with Transition can cause memory leaks in certain Vue versions
|
||||
type: gotcha
|
||||
tags: [vue3, keepalive, transition, memory-leak, animation]
|
||||
---
|
||||
|
||||
# KeepAlive with Transition Memory Leak
|
||||
|
||||
**Impact: MEDIUM** - There is a known memory leak when using `<Transition>` and `<KeepAlive>` together. Component instances may not be properly freed from memory when combining these features.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Test memory behavior when using KeepAlive + Transition together
|
||||
- [ ] Consider if transition animation is necessary with cached components
|
||||
- [ ] Use browser DevTools Memory tab to verify no leak
|
||||
- [ ] Keep Vue updated to get latest bug fixes
|
||||
|
||||
## The Problem
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Known memory leak combination in some Vue versions -->
|
||||
<Transition name="fade">
|
||||
<KeepAlive>
|
||||
<component :is="currentView" />
|
||||
</KeepAlive>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
When switching between components repeatedly:
|
||||
- Component instances accumulate in memory
|
||||
- References prevent garbage collection
|
||||
- Memory usage grows with each switch
|
||||
|
||||
## Diagnosis
|
||||
|
||||
Use Chrome DevTools to detect the leak:
|
||||
|
||||
1. Open DevTools > Memory tab
|
||||
2. Take heap snapshot
|
||||
3. Switch between components 10+ times
|
||||
4. Take another heap snapshot
|
||||
5. Compare: look for growing VueComponent count
|
||||
|
||||
## Workarounds
|
||||
|
||||
### Option 1: Remove Transition if Not Essential
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- No memory leak without Transition -->
|
||||
<KeepAlive :max="5">
|
||||
<component :is="currentView" />
|
||||
</KeepAlive>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 2: Use CSS Animations Instead
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<KeepAlive :max="5">
|
||||
<component
|
||||
:is="currentView"
|
||||
:class="{ 'fade-enter': isTransitioning }"
|
||||
/>
|
||||
</KeepAlive>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.fade-enter {
|
||||
animation: fadeIn 0.3s ease-in;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Option 3: Use Strict Cache Limits
|
||||
|
||||
If you must use both, minimize impact with strict limits:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<Transition name="fade" mode="out-in">
|
||||
<KeepAlive :max="3">
|
||||
<component :is="currentView" />
|
||||
</KeepAlive>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Option 4: Key-Based Cache Invalidation
|
||||
|
||||
Force fresh instances when needed:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const currentView = ref('Dashboard')
|
||||
const cacheKey = ref(0)
|
||||
|
||||
function switchViewFresh(view) {
|
||||
currentView.value = view
|
||||
cacheKey.value++ // Force new instance
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition name="fade" mode="out-in">
|
||||
<KeepAlive :max="3">
|
||||
<component :is="currentView" :key="cacheKey" />
|
||||
</KeepAlive>
|
||||
</Transition>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Keep Vue Updated
|
||||
|
||||
This is a known issue tracked in Vue's GitHub repository. Memory leak fixes are periodically released, so ensure you're on the latest Vue version:
|
||||
|
||||
```bash
|
||||
npm update vue
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
1. **Known issue** - Memory leaks with KeepAlive + Transition are documented
|
||||
2. **Test in DevTools** - Use Memory tab to verify your specific usage
|
||||
3. **Consider alternatives** - CSS animations may work without the leak
|
||||
4. **Set strict `max`** - Limit cache size to cap memory impact
|
||||
5. **Keep Vue updated** - Bug fixes are released periodically
|
||||
|
||||
## Reference
|
||||
- [GitHub Issue #9842: Memory leak with transition and keep-alive](https://github.com/vuejs/vue/issues/9842)
|
||||
- [GitHub Issue #9840: Memory leak with transition and keep-alive](https://github.com/vuejs/vue/issues/9840)
|
||||
- [Vue.js KeepAlive Documentation](https://vuejs.org/guide/built-ins/keep-alive.html)
|
||||
@@ -0,0 +1,137 @@
|
||||
---
|
||||
title: System Modifier Keys Must Be Held During keyup Events
|
||||
impact: MEDIUM
|
||||
impactDescription: Modifier keys (ctrl, alt, shift, meta) behave differently with keyup - they must be held when the key is released
|
||||
type: gotcha
|
||||
tags: [vue3, events, keyboard, modifiers, keyup, shortcuts]
|
||||
---
|
||||
|
||||
# System Modifier Keys Must Be Held During keyup Events
|
||||
|
||||
**Impact: MEDIUM** - When using system modifier keys (`.ctrl`, `.alt`, `.shift`, `.meta`) with `keyup` events, the modifier must still be pressed when the other key is released. Releasing the modifier key first will not trigger the event, causing keyboard shortcuts to appear broken.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Understand that `@keyup.ctrl` requires Ctrl to be held while releasing another key
|
||||
- [ ] Consider using `keydown` instead of `keyup` for modifier key combinations
|
||||
- [ ] Use `.exact` when you need precise modifier key control
|
||||
- [ ] Test keyboard shortcuts with proper key release order
|
||||
|
||||
**Incorrect:**
|
||||
```html
|
||||
<!-- WRONG: Expecting this to fire when Ctrl is released -->
|
||||
<template>
|
||||
<input @keyup.ctrl="onCtrlRelease" />
|
||||
<!-- This does NOT fire when you just release Ctrl! -->
|
||||
<!-- It fires when you release ANY key while holding Ctrl -->
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Misunderstanding keyup.ctrl behavior -->
|
||||
<template>
|
||||
<div @keyup.ctrl="handleShortcut">
|
||||
<!-- User presses Ctrl+S, releases Ctrl first, then S -->
|
||||
<!-- Event does NOT fire because Ctrl wasn't held during S release -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- CORRECT: User must hold Ctrl while releasing another key -->
|
||||
<template>
|
||||
<input @keyup.ctrl.s="saveDocument" />
|
||||
<!-- User presses Ctrl+S, then releases S while holding Ctrl -->
|
||||
<!-- Event fires correctly -->
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
function saveDocument(event) {
|
||||
event.preventDefault()
|
||||
// Save logic here
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Use keydown for more intuitive modifier behavior -->
|
||||
<template>
|
||||
<div @keydown.ctrl.s="saveDocument">
|
||||
<!-- keydown fires immediately when both keys are pressed -->
|
||||
<!-- More intuitive for keyboard shortcuts -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Use .exact for precise modifier control -->
|
||||
<template>
|
||||
<!-- Only fires when ONLY Ctrl is pressed (no Shift, Alt, etc.) -->
|
||||
<button @click.ctrl.exact="onCtrlClick">Ctrl+Click Only</button>
|
||||
|
||||
<!-- Fires with no system modifiers at all -->
|
||||
<button @click.exact="onPlainClick">Plain Click Only</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## How System Modifiers Work with keyup
|
||||
|
||||
```javascript
|
||||
// Timeline of Ctrl+S keydown:
|
||||
// 1. User presses Ctrl (keydown fires)
|
||||
// 2. User presses S while holding Ctrl (keydown fires)
|
||||
|
||||
// Timeline of Ctrl+S keyup:
|
||||
// 3. User releases S while holding Ctrl (keyup.ctrl.s fires!)
|
||||
// 4. User releases Ctrl (keyup fires, but not keyup.ctrl.s)
|
||||
|
||||
// Common mistake:
|
||||
// 3. User releases Ctrl first (nothing fires for our handler)
|
||||
// 4. User releases S (keyup.s fires, but not keyup.ctrl.s)
|
||||
```
|
||||
|
||||
## System Modifier Keys
|
||||
|
||||
```html
|
||||
<!-- Available system modifiers -->
|
||||
<input @keyup.ctrl="..." /> <!-- Ctrl key -->
|
||||
<input @keyup.alt="..." /> <!-- Alt key (Option on Mac) -->
|
||||
<input @keyup.shift="..." /> <!-- Shift key -->
|
||||
<input @keyup.meta="..." /> <!-- Cmd on Mac, Windows key on PC -->
|
||||
```
|
||||
|
||||
## The .exact Modifier
|
||||
|
||||
```html
|
||||
<!-- Different .exact behaviors -->
|
||||
|
||||
<!-- Fires even if Shift/Alt are also pressed -->
|
||||
<button @click.ctrl="onClick">Ctrl + any other modifiers</button>
|
||||
|
||||
<!-- Fires ONLY when Ctrl alone is pressed -->
|
||||
<button @click.ctrl.exact="onClick">Ctrl only, no other modifiers</button>
|
||||
|
||||
<!-- Fires ONLY when no system modifiers are pressed -->
|
||||
<button @click.exact="onClick">No modifiers allowed</button>
|
||||
```
|
||||
|
||||
## Best Practice: Prefer keydown for Shortcuts
|
||||
|
||||
```html
|
||||
<template>
|
||||
<div
|
||||
tabindex="0"
|
||||
@keydown.ctrl.s.prevent="save"
|
||||
@keydown.ctrl.z.prevent="undo"
|
||||
@keydown.ctrl.shift.z.prevent="redo"
|
||||
>
|
||||
<!-- keydown is more reliable for keyboard shortcuts -->
|
||||
<!-- Add .prevent to stop browser default (e.g., save dialog) -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Event Handling - Key Modifiers](https://vuejs.org/guide/essentials/event-handling.html#key-modifiers)
|
||||
- [Vue.js Event Handling - System Modifier Keys](https://vuejs.org/guide/essentials/event-handling.html#system-modifier-keys)
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
title: Access DOM Only After Mounted Hook
|
||||
impact: HIGH
|
||||
impactDescription: Accessing DOM elements before mounted causes undefined errors and silent failures
|
||||
type: capability
|
||||
tags: [vue3, vue2, lifecycle, dom, mounted, created, beforeMount, template-refs]
|
||||
---
|
||||
|
||||
# Access DOM Only After Mounted Hook
|
||||
|
||||
**Impact: HIGH** - Attempting to access DOM elements or `this.$el` in `created` or `beforeMount` hooks fails because the component's template has not yet been rendered to the DOM. This leads to undefined errors, null references, and failed third-party library initializations.
|
||||
|
||||
The component's DOM is only available starting from the `mounted` hook (Options API) or after `onMounted` runs (Composition API). Before this point, `this.$el` is undefined and template refs are null.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Perform DOM manipulations only in `mounted`/`onMounted` or later
|
||||
- [ ] Initialize DOM-dependent libraries (charts, maps, editors) in mounted
|
||||
- [ ] Use `created` for data initialization and API calls (non-DOM operations)
|
||||
- [ ] Access template refs only after mounted
|
||||
- [ ] Use `$nextTick` if you need DOM after reactive data changes
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// WRONG: Accessing DOM in created hook
|
||||
export default {
|
||||
created() {
|
||||
// DOM doesn't exist yet!
|
||||
console.log(this.$el) // undefined
|
||||
this.$el.querySelector('.chart') // Error: Cannot read property 'querySelector' of undefined
|
||||
|
||||
// Third-party library initialization fails
|
||||
new Chart(document.getElementById('myChart')) // Element doesn't exist yet
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// WRONG: Accessing DOM in beforeMount
|
||||
export default {
|
||||
beforeMount() {
|
||||
// Still too early - template is compiled but not mounted
|
||||
console.log(this.$el) // undefined in Vue 3
|
||||
this.$refs.myInput.focus() // Error: Cannot read property 'focus' of undefined
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- WRONG: Accessing template ref synchronously in setup -->
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const myInput = ref(null)
|
||||
|
||||
// This runs during setup, before mounting
|
||||
myInput.value.focus() // Error: Cannot read property 'focus' of null
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="myInput" />
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// CORRECT: Use created for data, mounted for DOM
|
||||
export default {
|
||||
data() {
|
||||
return { chartData: null }
|
||||
},
|
||||
async created() {
|
||||
// Data fetching is fine in created
|
||||
this.chartData = await fetchChartData()
|
||||
},
|
||||
mounted() {
|
||||
// Now the DOM exists and is safe to access
|
||||
console.log(this.$el) // <div>...</div>
|
||||
|
||||
// Initialize DOM-dependent libraries
|
||||
this.chart = new Chart(this.$refs.chartCanvas, {
|
||||
data: this.chartData
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- CORRECT: Access template refs in onMounted -->
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const myInput = ref(null)
|
||||
|
||||
onMounted(() => {
|
||||
// DOM is now available
|
||||
myInput.value.focus() // Works!
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="myInput" />
|
||||
</template>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// CORRECT: Using $nextTick for DOM access after data changes
|
||||
export default {
|
||||
methods: {
|
||||
async addItem() {
|
||||
this.items.push(newItem)
|
||||
|
||||
// Wait for Vue to update the DOM
|
||||
await this.$nextTick()
|
||||
|
||||
// Now the new element exists in DOM
|
||||
this.$refs.list.lastElementChild.scrollIntoView()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Vue 3 Composition API Pattern
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted, nextTick } from 'vue'
|
||||
|
||||
const listRef = ref(null)
|
||||
const items = ref([])
|
||||
|
||||
onMounted(() => {
|
||||
// Safe to access DOM here
|
||||
listRef.value.style.height = '400px'
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Vue 3.5+ useTemplateRef Pattern
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useTemplateRef, onMounted } from 'vue'
|
||||
|
||||
// Vue 3.5+ recommended approach - decouples ref name from variable name
|
||||
const input = useTemplateRef('my-input')
|
||||
|
||||
onMounted(() => {
|
||||
input.value.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="my-input" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Composition API with nextTick
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, nextTick } from 'vue'
|
||||
|
||||
const listRef = ref(null)
|
||||
const items = ref([])
|
||||
|
||||
async function addItem(item) {
|
||||
items.value.push(item)
|
||||
|
||||
// Wait for DOM update after reactive change
|
||||
await nextTick()
|
||||
|
||||
// Now new item is in DOM
|
||||
listRef.value.lastElementChild.focus()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul ref="listRef">
|
||||
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
|
||||
</ul>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Common Third-Party Libraries
|
||||
|
||||
```javascript
|
||||
// CORRECT: Initialize in mounted
|
||||
export default {
|
||||
mounted() {
|
||||
// Chart.js
|
||||
this.chart = new Chart(this.$refs.canvas, config)
|
||||
|
||||
// Leaflet maps
|
||||
this.map = L.map(this.$refs.mapContainer).setView([51.505, -0.09], 13)
|
||||
|
||||
// Monaco Editor
|
||||
this.editor = monaco.editor.create(this.$refs.editorContainer, options)
|
||||
|
||||
// Video.js
|
||||
this.player = videojs(this.$refs.videoElement)
|
||||
},
|
||||
beforeUnmount() {
|
||||
// Don't forget cleanup!
|
||||
this.chart?.destroy()
|
||||
this.map?.remove()
|
||||
this.editor?.dispose()
|
||||
this.player?.dispose()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html)
|
||||
- [Vue.js Template Refs](https://vuejs.org/guide/essentials/template-refs.html)
|
||||
- [Vue.js nextTick](https://vuejs.org/api/general.html#nexttick)
|
||||
@@ -0,0 +1,156 @@
|
||||
---
|
||||
title: Register Lifecycle Hooks Synchronously During Setup
|
||||
impact: HIGH
|
||||
impactDescription: Asynchronously registered lifecycle hooks will never execute
|
||||
type: capability
|
||||
tags: [vue3, composition-api, lifecycle, onMounted, onUnmounted, async, setup]
|
||||
---
|
||||
|
||||
# Register Lifecycle Hooks Synchronously During Setup
|
||||
|
||||
**Impact: HIGH** - Lifecycle hooks registered asynchronously (e.g., inside setTimeout, after await) will never be called because Vue cannot associate them with the component instance. This leads to silent failures where expected initialization or cleanup code never runs.
|
||||
|
||||
In Vue 3's Composition API, lifecycle hooks like `onMounted`, `onUnmounted`, `onUpdated`, etc. must be registered synchronously during component setup. The hook registration doesn't need to be lexically inside `setup()` or `<script setup>`, but the call stack must be synchronous and originate from within setup.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Register all lifecycle hooks at the top level of setup() or `<script setup>`
|
||||
- [ ] Never register hooks inside setTimeout, setInterval, or Promise callbacks
|
||||
- [ ] When calling composables that use lifecycle hooks, call them synchronously
|
||||
- [ ] Hooks CAN be in external functions if called synchronously from setup
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// WRONG: Hook registered asynchronously - will NEVER execute
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
export default {
|
||||
async setup() {
|
||||
// After await, we're in a different call stack
|
||||
const data = await fetchInitialData()
|
||||
|
||||
// This hook will NOT be registered!
|
||||
onMounted(() => {
|
||||
console.log('This will never run')
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// WRONG: Hook registered in setTimeout - will NEVER execute
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
setTimeout(() => {
|
||||
// This is asynchronous - hook won't be registered!
|
||||
onMounted(() => {
|
||||
initializeChart()
|
||||
})
|
||||
}, 100)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// WRONG: Hook registered in Promise callback
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
fetchConfig().then(() => {
|
||||
// Asynchronous! This will silently fail
|
||||
onMounted(() => {
|
||||
applyConfig()
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// CORRECT: Hook registered synchronously at top level
|
||||
import { onMounted, ref } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const data = ref(null)
|
||||
|
||||
// Register hook synchronously FIRST
|
||||
onMounted(async () => {
|
||||
// Async operations are fine INSIDE the hook
|
||||
data.value = await fetchInitialData()
|
||||
initializeChart()
|
||||
})
|
||||
|
||||
return { data }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- CORRECT: <script setup> - hooks at top level -->
|
||||
<script setup>
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
|
||||
const isReady = ref(false)
|
||||
|
||||
// These are synchronous during script setup execution
|
||||
onMounted(() => {
|
||||
isReady.value = true
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
cleanup()
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// CORRECT: Hook in external function called synchronously from setup
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
|
||||
function useWindowResize(callback) {
|
||||
// This is fine - it's called synchronously from setup
|
||||
onMounted(() => {
|
||||
window.addEventListener('resize', callback)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', callback)
|
||||
})
|
||||
}
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
// Composable called synchronously - hooks will be registered
|
||||
useWindowResize(handleResize)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Multiple Hooks Are Allowed
|
||||
|
||||
```javascript
|
||||
// CORRECT: You can register the same hook multiple times
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
// Both will run, in order of registration
|
||||
onMounted(() => {
|
||||
initializeA()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
initializeB()
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html)
|
||||
- [Composition API Lifecycle Hooks](https://vuejs.org/api/composition-api-lifecycle.html)
|
||||
@@ -0,0 +1,184 @@
|
||||
---
|
||||
title: Mounted and Unmounted Hooks Do Not Run During SSR
|
||||
impact: MEDIUM
|
||||
impactDescription: SSR applications may fail if mounted-only code is essential for functionality
|
||||
type: capability
|
||||
tags: [vue3, lifecycle, ssr, server-side-rendering, nuxt, onMounted, mounted, hydration]
|
||||
---
|
||||
|
||||
# Mounted and Unmounted Hooks Do Not Run During SSR
|
||||
|
||||
**Impact: MEDIUM** - During server-side rendering (SSR), lifecycle hooks like `mounted`, `onMounted`, `unmounted`, and `onUnmounted` are never called on the server. This can cause differences between server-rendered and client-rendered content, hydration mismatches, and missing functionality if critical logic is placed only in these hooks.
|
||||
|
||||
On the server, only `beforeCreate`, `created`, and their Composition API equivalents run. Client-specific operations (DOM access, browser APIs, third-party libraries) must be in mounted hooks, but you must handle the SSR case appropriately.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Place browser-specific code (window, document, localStorage) in mounted/onMounted
|
||||
- [ ] Ensure critical data fetching happens in hooks that run on server (created)
|
||||
- [ ] Handle hydration mismatches for content that differs client vs server
|
||||
- [ ] Use `<ClientOnly>` wrapper (Nuxt) or conditional rendering for client-only components
|
||||
- [ ] Check for browser environment before using browser APIs
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
// WRONG: Accessing browser APIs in created - breaks SSR
|
||||
export default {
|
||||
created() {
|
||||
// These don't exist on the server!
|
||||
this.width = window.innerWidth // ReferenceError: window is not defined
|
||||
this.savedData = localStorage.getItem('data') // ReferenceError: localStorage is not defined
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// WRONG: Critical initialization only in mounted - won't run on server
|
||||
export default {
|
||||
data() {
|
||||
return { user: null }
|
||||
},
|
||||
async mounted() {
|
||||
// This won't run on server - page renders without user data
|
||||
// Then hydrates with user data - causes flash of content
|
||||
this.user = await fetchCurrentUser()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
// CORRECT: Data fetching in created (runs on server), DOM in mounted
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
user: null,
|
||||
windowWidth: 0
|
||||
}
|
||||
},
|
||||
async created() {
|
||||
// This runs on both server and client
|
||||
this.user = await fetchCurrentUser()
|
||||
},
|
||||
mounted() {
|
||||
// Browser-specific code safely in mounted
|
||||
this.windowWidth = window.innerWidth
|
||||
window.addEventListener('resize', this.handleResize)
|
||||
},
|
||||
unmounted() {
|
||||
window.removeEventListener('resize', this.handleResize)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- CORRECT: Composition API with SSR awareness -->
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
const user = ref(null)
|
||||
const windowWidth = ref(0)
|
||||
|
||||
// This runs on both server and client (during setup)
|
||||
user.value = await useFetch('/api/user')
|
||||
|
||||
// These only run on client
|
||||
onMounted(() => {
|
||||
windowWidth.value = window.innerWidth
|
||||
window.addEventListener('resize', handleResize)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
})
|
||||
|
||||
function handleResize() {
|
||||
windowWidth.value = window.innerWidth
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Checking for Browser Environment
|
||||
|
||||
```javascript
|
||||
// CORRECT: Guard browser API access
|
||||
export default {
|
||||
data() {
|
||||
return { theme: 'light' }
|
||||
},
|
||||
created() {
|
||||
// Check if we're in browser before accessing browser APIs
|
||||
if (typeof window !== 'undefined') {
|
||||
this.theme = localStorage.getItem('theme') || 'light'
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
// mounted only runs in browser, so this is always safe
|
||||
this.applyTheme()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Nuxt.js Specific Patterns
|
||||
|
||||
```vue
|
||||
<!-- CORRECT: Using Nuxt's ClientOnly for client-specific components -->
|
||||
<template>
|
||||
<div>
|
||||
<!-- This content renders on both server and client -->
|
||||
<h1>Dashboard</h1>
|
||||
|
||||
<!-- This only renders on client - no hydration mismatch -->
|
||||
<ClientOnly>
|
||||
<ChartComponent :data="chartData" />
|
||||
<template #fallback>
|
||||
<p>Loading chart...</p>
|
||||
</template>
|
||||
</ClientOnly>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// CORRECT: Using Nuxt's process.client/process.server
|
||||
export default {
|
||||
created() {
|
||||
if (process.client) {
|
||||
// Only runs in browser
|
||||
this.initAnalytics()
|
||||
}
|
||||
if (process.server) {
|
||||
// Only runs on server
|
||||
this.logServerRequest()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Handling Hydration Mismatches
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
// Start with a value that matches what server renders
|
||||
const currentTime = ref(null)
|
||||
|
||||
onMounted(() => {
|
||||
// Update to real value only on client
|
||||
// This prevents hydration mismatch
|
||||
currentTime.value = new Date().toLocaleTimeString()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Renders null on server, then updates on client -->
|
||||
<span v-if="currentTime">{{ currentTime }}</span>
|
||||
<span v-else>Loading...</span>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js SSR Guide](https://vuejs.org/guide/scaling-up/ssr.html)
|
||||
- [Nuxt.js Lifecycle](https://nuxt.com/docs/api/composables/use-nuxt-app#lifecycle-hooks)
|
||||
- [Vue SSR Hydration](https://vuejs.org/guide/scaling-up/ssr.html#client-hydration)
|
||||
@@ -0,0 +1,151 @@
|
||||
---
|
||||
title: Locally Registered Components Are Not Available in Descendants
|
||||
impact: HIGH
|
||||
impactDescription: Common source of "component not found" errors in nested components
|
||||
type: gotcha
|
||||
tags: [vue3, component-registration, local-registration, scope, nested-components]
|
||||
---
|
||||
|
||||
# Locally Registered Components Are Not Available in Descendants
|
||||
|
||||
**Impact: HIGH** - Locally registered components are only available in the component where they are registered, NOT in its child or descendant components. This is a common source of "Unknown component" or "Failed to resolve component" errors when developers expect a component registered in a parent to be available in children.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Import and register components in every file where they are used
|
||||
- [ ] Do not expect parent's local components to be available in children
|
||||
- [ ] If a component is needed in many places, consider global registration only as a last resort
|
||||
- [ ] Use IDE auto-import features to simplify repeated imports
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import Card from './Card.vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>Parent content</Card>
|
||||
<ChildComponent />
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
// WRONG: Expecting Card to be available because parent imported it
|
||||
// This will cause "Failed to resolve component: Card" error
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- ERROR: Card is not available here! -->
|
||||
<Card>
|
||||
Child content
|
||||
</Card>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<!-- ParentComponent.vue -->
|
||||
<script setup>
|
||||
import Card from './Card.vue'
|
||||
import ChildComponent from './ChildComponent.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>Parent content</Card>
|
||||
<ChildComponent />
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ChildComponent.vue -->
|
||||
<script setup>
|
||||
// CORRECT: Each component must import what it uses
|
||||
import Card from './Card.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
Child content
|
||||
</Card>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario 1: Deeply Nested Components
|
||||
```vue
|
||||
<!-- GrandchildComponent.vue -->
|
||||
<script setup>
|
||||
// Even if parent and grandparent both use Card,
|
||||
// grandchild must import it separately
|
||||
import Card from '@/components/Card.vue'
|
||||
import Button from '@/components/Button.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<Button>Click me</Button>
|
||||
</Card>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Scenario 2: Slot Content with Components
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<script setup>
|
||||
import Modal from './Modal.vue'
|
||||
import Form from './Form.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Form is registered in Parent, so it works in slot content -->
|
||||
<Modal>
|
||||
<Form /> <!-- This works because slot content is compiled in Parent's scope -->
|
||||
</Modal>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Modal.vue -->
|
||||
<script setup>
|
||||
// Modal doesn't need to import Form because slot content
|
||||
// is compiled in the parent's scope, not Modal's scope
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal">
|
||||
<slot /> <!-- Form component works here because it's parent's slot content -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Scenario 3: Dynamic Components
|
||||
```vue
|
||||
<!-- Container.vue -->
|
||||
<script setup>
|
||||
import TabA from './TabA.vue'
|
||||
import TabB from './TabB.vue'
|
||||
import { ref, shallowRef } from 'vue'
|
||||
|
||||
// When using dynamic components, all possible components must be imported
|
||||
const currentTab = shallowRef(TabA)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<component :is="currentTab" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Why This Design?
|
||||
|
||||
Local registration provides:
|
||||
1. **Explicit dependencies** - You can see exactly what each component uses
|
||||
2. **Tree-shaking** - Unused components are removed from bundles
|
||||
3. **Clear scope** - No magic or implicit behavior
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component Registration - Local Registration](https://vuejs.org/guide/components/registration.html#local-registration)
|
||||
@@ -0,0 +1,88 @@
|
||||
---
|
||||
title: mount() Returns Component Instance, Not App Instance
|
||||
impact: MEDIUM
|
||||
impactDescription: Using mount() return value for app configuration silently fails
|
||||
type: capability
|
||||
tags: [vue3, createApp, mount, api]
|
||||
---
|
||||
|
||||
# mount() Returns Component Instance, Not App Instance
|
||||
|
||||
**Impact: MEDIUM** - The `.mount()` method returns the root component instance, not the application instance. Attempting to chain app configuration methods after mount() will fail or produce unexpected behavior.
|
||||
|
||||
This is a subtle API detail that catches developers who assume mount() returns the app for continued chaining.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Never chain app configuration methods after mount()
|
||||
- [ ] If you need both instances, store them separately
|
||||
- [ ] Use the component instance for accessing root component state or methods
|
||||
- [ ] Use the app instance for configuration, plugins, and global registration
|
||||
|
||||
**Incorrect:**
|
||||
```javascript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
// WRONG: Assuming mount returns app instance
|
||||
const app = createApp(App).mount('#app')
|
||||
|
||||
// This fails! app is actually the root component instance
|
||||
app.use(router) // TypeError: app.use is not a function
|
||||
app.config.errorHandler = fn // app.config is undefined
|
||||
```
|
||||
|
||||
```javascript
|
||||
// WRONG: Trying to save both in one line
|
||||
const { app, component } = createApp(App).mount('#app') // Doesn't work this way
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```javascript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
// Store app instance separately
|
||||
const app = createApp(App)
|
||||
|
||||
// Configure the app
|
||||
app.use(router)
|
||||
app.config.errorHandler = (err) => console.error(err)
|
||||
|
||||
// Store component instance if needed
|
||||
const rootComponent = app.mount('#app')
|
||||
|
||||
// Now you have access to both:
|
||||
// - app: the application instance (for config, plugins)
|
||||
// - rootComponent: the root component instance (for state, methods)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// If you only need the app configured and mounted (most common case):
|
||||
createApp(App)
|
||||
.use(router)
|
||||
.use(pinia)
|
||||
.mount('#app') // Return value (component instance) discarded - that's fine
|
||||
```
|
||||
|
||||
## When You Need the Root Component Instance
|
||||
|
||||
```javascript
|
||||
const app = createApp(App)
|
||||
const vm = app.mount('#app')
|
||||
|
||||
// Access root component's exposed state/methods
|
||||
console.log(vm.someExposedProperty)
|
||||
vm.someExposedMethod()
|
||||
|
||||
// In Vue 3 with <script setup>, use defineExpose to expose:
|
||||
// <script setup>
|
||||
// import { ref } from 'vue'
|
||||
// const count = ref(0)
|
||||
// defineExpose({ count })
|
||||
// </script>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js - Mounting the App](https://vuejs.org/guide/essentials/application.html#mounting-the-app)
|
||||
- [Vue.js Application API - mount()](https://vuejs.org/api/application.html#app-mount)
|
||||
@@ -0,0 +1,93 @@
|
||||
# Multi-Root Component Class Attribute Inheritance
|
||||
|
||||
## Rule
|
||||
|
||||
When a Vue 3 component has multiple root elements, class and style bindings from the parent will NOT automatically fall through. You must explicitly bind `$attrs.class` or `$attrs.style` to the target element.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
- Vue 3 components can have multiple root elements (fragments)
|
||||
- Unlike single-root components, multi-root components have no automatic attribute fallthrough
|
||||
- Without explicit handling, classes and styles passed from parent are silently ignored
|
||||
- Vue will emit a runtime warning, but styles/classes simply won't apply
|
||||
|
||||
## Bad Code
|
||||
|
||||
```vue
|
||||
<!-- ChildComponent.vue - WRONG: classes from parent won't apply -->
|
||||
<template>
|
||||
<header>Header</header>
|
||||
<main>Content</main>
|
||||
<footer>Footer</footer>
|
||||
</template>
|
||||
|
||||
<!-- Parent usage -->
|
||||
<ChildComponent class="my-custom-class" />
|
||||
<!-- Result: my-custom-class is NOT applied to any element -->
|
||||
```
|
||||
|
||||
## Good Code
|
||||
|
||||
```vue
|
||||
<!-- ChildComponent.vue - CORRECT: explicitly bind $attrs.class -->
|
||||
<template>
|
||||
<header>Header</header>
|
||||
<main :class="$attrs.class" :style="$attrs.style">Content</main>
|
||||
<footer>Footer</footer>
|
||||
</template>
|
||||
|
||||
<!-- Or bind all attrs to one element -->
|
||||
<template>
|
||||
<header>Header</header>
|
||||
<main v-bind="$attrs">Content</main>
|
||||
<footer>Footer</footer>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Accessing $attrs in script setup
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useAttrs } from 'vue'
|
||||
const attrs = useAttrs()
|
||||
// attrs.class and attrs.style are available
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header>Header</header>
|
||||
<main :class="attrs.class">Content</main>
|
||||
<footer>Footer</footer>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Disabling Automatic Inheritance
|
||||
|
||||
For single-root components where you want to control attribute placement:
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
inheritAttrs: false
|
||||
}
|
||||
</script>
|
||||
|
||||
<script setup>
|
||||
import { useAttrs } from 'vue'
|
||||
const attrs = useAttrs()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="wrapper">
|
||||
<input v-bind="attrs" />
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Vue 2 to Vue 3 Migration Note
|
||||
|
||||
In Vue 2, `$attrs` did NOT include `class` and `style`. In Vue 3, `$attrs` contains ALL attributes including `class` and `style`. This is a breaking change that affects how you handle attribute forwarding.
|
||||
|
||||
## References
|
||||
|
||||
- [Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
|
||||
- [Vue 3 Migration Guide - $attrs includes class & style](https://v3-migration.vuejs.org/breaking-changes/attrs-includes-class-style)
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
title: Declaring Native Event Names in Emits Blocks Native Listeners
|
||||
impact: MEDIUM
|
||||
impactDescription: Declaring native events like 'click' in emits prevents native DOM event listeners from working
|
||||
type: gotcha
|
||||
tags: [vue3, emits, native-events, click, event-collision]
|
||||
---
|
||||
|
||||
# Declaring Native Event Names in Emits Blocks Native Listeners
|
||||
|
||||
**Impact: MEDIUM** - When you declare a native DOM event name (like `click`, `input`, `focus`) in your component's `emits` option, listeners for that event will ONLY respond to your component's `emit()` calls. They will no longer respond to the actual native DOM events on the root element.
|
||||
|
||||
This can cause unexpected behavior where clicks seem to stop working on your component.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Understand that declaring native event names changes listener behavior
|
||||
- [ ] Always emit the event when you declare it
|
||||
- [ ] Don't declare native events if you want fallthrough behavior
|
||||
- [ ] Test click/input handling after adding emits declarations
|
||||
|
||||
## The Problem
|
||||
|
||||
**Incorrect - Declaring but not emitting:**
|
||||
```vue
|
||||
<!-- ClickableCard.vue -->
|
||||
<script setup>
|
||||
// Declared 'click' but never emit it!
|
||||
const emit = defineEmits(['click', 'select'])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="card">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<!-- This NEVER fires! Native clicks are blocked -->
|
||||
<ClickableCard @click="handleClick">
|
||||
Click me
|
||||
</ClickableCard>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Why it fails:**
|
||||
1. `click` is declared in `emits`
|
||||
2. Vue treats `@click` as a component event listener
|
||||
3. Native click on the `<div>` doesn't trigger component event
|
||||
4. Since `emit('click')` is never called, handler never fires
|
||||
|
||||
## The Solution
|
||||
|
||||
**Option 1: Emit the event explicitly:**
|
||||
```vue
|
||||
<!-- ClickableCard.vue -->
|
||||
<script setup>
|
||||
const emit = defineEmits(['click', 'select'])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Explicitly emit click when div is clicked -->
|
||||
<div class="card" @click="emit('click', $event)">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Option 2: Don't declare native events (use fallthrough):**
|
||||
```vue
|
||||
<!-- ClickableCard.vue -->
|
||||
<script setup>
|
||||
// Only declare custom events, not native ones
|
||||
const emit = defineEmits(['select', 'custom-action'])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Native @click from parent falls through to this div -->
|
||||
<div class="card">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Parent.vue -->
|
||||
<template>
|
||||
<!-- Native click falls through and works -->
|
||||
<ClickableCard @click="handleClick">
|
||||
Click me
|
||||
</ClickableCard>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Native Events Affected
|
||||
|
||||
This applies to any native DOM event you might declare:
|
||||
|
||||
| Event | Behavior When Declared |
|
||||
|-------|----------------------|
|
||||
| `click` | Only responds to `emit('click')`, not native clicks |
|
||||
| `input` | Only responds to `emit('input')`, not native input |
|
||||
| `change` | Only responds to `emit('change')`, not native change |
|
||||
| `focus` | Only responds to `emit('focus')`, not native focus |
|
||||
| `blur` | Only responds to `emit('blur')`, not native blur |
|
||||
| `submit` | Only responds to `emit('submit')`, not native form submit |
|
||||
| `keydown` | Only responds to `emit('keydown')`, not native keydown |
|
||||
|
||||
## When This Is Intentional
|
||||
|
||||
Sometimes you WANT to intercept native events:
|
||||
|
||||
```vue
|
||||
<!-- CustomInput.vue -->
|
||||
<script setup>
|
||||
// Intentionally intercept 'input' to transform the value
|
||||
const emit = defineEmits(['input', 'update:modelValue'])
|
||||
|
||||
function handleInput(event) {
|
||||
const transformedValue = event.target.value.toUpperCase()
|
||||
emit('input', transformedValue) // Emit transformed value, not raw event
|
||||
emit('update:modelValue', transformedValue)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input @input="handleInput" />
|
||||
</template>
|
||||
```
|
||||
|
||||
Here, declaring `input` is correct because you want to intercept and transform the native event before passing it to the parent.
|
||||
|
||||
## Debugging Tips
|
||||
|
||||
If your click handlers aren't firing:
|
||||
|
||||
1. Check if the event is declared in `emits`
|
||||
2. If declared, ensure you're calling `emit('click')` somewhere
|
||||
3. If you want native behavior, remove from `emits` declaration
|
||||
4. Use Vue DevTools to see which events are being emitted
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const emit = defineEmits(['click'])
|
||||
|
||||
function handleClick(event) {
|
||||
console.log('Native click received, now emitting component event')
|
||||
emit('click', event)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div @click="handleClick">Click me</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Component Events](https://vuejs.org/guide/components/events.html)
|
||||
- [Vue.js Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
|
||||
@@ -0,0 +1,141 @@
|
||||
---
|
||||
title: Never Use .passive and .prevent Together
|
||||
impact: HIGH
|
||||
impactDescription: Conflicting modifiers cause .prevent to be ignored and trigger browser warnings
|
||||
type: gotcha
|
||||
tags: [vue3, events, modifiers, scroll, touch, performance]
|
||||
---
|
||||
|
||||
# Never Use .passive and .prevent Together
|
||||
|
||||
**Impact: HIGH** - The `.passive` modifier tells the browser you will NOT call `preventDefault()`, while `.prevent` does exactly that. Using them together causes `.prevent` to be ignored and triggers browser console warnings. This is a logical contradiction that leads to broken event handling.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Never combine `.passive` and `.prevent` on the same event
|
||||
- [ ] Use `.passive` for scroll/touch events where you want better performance
|
||||
- [ ] Use `.prevent` when you need to stop the default browser action
|
||||
- [ ] If you need conditional prevention, handle it in JavaScript without `.passive`
|
||||
|
||||
**Incorrect:**
|
||||
```html
|
||||
<!-- WRONG: Conflicting modifiers -->
|
||||
<template>
|
||||
<div @scroll.passive.prevent="handleScroll">
|
||||
<!-- .prevent will be IGNORED -->
|
||||
<!-- Browser shows warning -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: On touch events -->
|
||||
<template>
|
||||
<div @touchstart.passive.prevent="handleTouch">
|
||||
<!-- Cannot prevent default - passive already promised not to -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: On wheel events -->
|
||||
<template>
|
||||
<div @wheel.passive.prevent="handleWheel">
|
||||
<!-- Broken: will scroll anyway despite .prevent -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- CORRECT: Use .passive for performance (no prevention needed) -->
|
||||
<template>
|
||||
<div @scroll.passive="handleScroll">
|
||||
<!-- Good for scroll tracking without blocking -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Use .prevent when you need to prevent default -->
|
||||
<template>
|
||||
<form @submit.prevent="handleSubmit">
|
||||
<!-- Correctly prevents form submission -->
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: For touch events where you need to prevent -->
|
||||
<template>
|
||||
<div @touchmove="handleTouchMove">
|
||||
<!-- Handle prevention conditionally in JS -->
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
function handleTouchMove(event) {
|
||||
if (shouldPreventScroll.value) {
|
||||
event.preventDefault()
|
||||
}
|
||||
// ... handle touch
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Understanding .passive
|
||||
|
||||
```javascript
|
||||
// .passive tells the browser:
|
||||
// "I promise I won't call preventDefault()"
|
||||
|
||||
// This allows the browser to:
|
||||
// 1. Start scrolling immediately without waiting for JS
|
||||
// 2. Improve scroll performance, especially on mobile
|
||||
// 3. Reduce jank and stuttering
|
||||
|
||||
// Equivalent to:
|
||||
element.addEventListener('scroll', handler, { passive: true })
|
||||
```
|
||||
|
||||
## When to Use .passive
|
||||
|
||||
```html
|
||||
<!-- Good use cases for .passive -->
|
||||
|
||||
<!-- Scroll tracking analytics -->
|
||||
<div @scroll.passive="trackScrollPosition">
|
||||
|
||||
<!-- Touch gesture detection (no prevention needed) -->
|
||||
<div @touchmove.passive="detectGesture">
|
||||
|
||||
<!-- Wheel event monitoring -->
|
||||
<div @wheel.passive="monitorWheel">
|
||||
```
|
||||
|
||||
## When to Use .prevent (Without .passive)
|
||||
|
||||
```html
|
||||
<!-- Good use cases for .prevent -->
|
||||
|
||||
<!-- Form submission -->
|
||||
<form @submit.prevent="handleSubmit">
|
||||
|
||||
<!-- Link clicks with custom navigation -->
|
||||
<a @click.prevent="navigate">
|
||||
|
||||
<!-- Preventing context menu -->
|
||||
<div @contextmenu.prevent="showCustomMenu">
|
||||
```
|
||||
|
||||
## Browser Warning
|
||||
|
||||
When you combine `.passive` and `.prevent`, the browser console shows:
|
||||
```
|
||||
[Intervention] Unable to preventDefault inside passive event listener
|
||||
due to target being treated as passive.
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Event Handling - Event Modifiers](https://vuejs.org/guide/essentials/event-handling.html#event-modifiers)
|
||||
- [MDN - Improving scroll performance with passive listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners)
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
title: Never Use v-if and v-for on the Same Element
|
||||
impact: HIGH
|
||||
impactDescription: Causes confusing precedence issues and Vue 2 to 3 migration bugs
|
||||
type: capability
|
||||
tags: [vue3, v-if, v-for, conditional-rendering, list-rendering, eslint]
|
||||
---
|
||||
|
||||
# Never Use v-if and v-for on the Same Element
|
||||
|
||||
**Impact: HIGH** - Using `v-if` and `v-for` on the same element creates ambiguous precedence that differs between Vue 2 and Vue 3. In Vue 2, `v-for` had higher precedence; in Vue 3, `v-if` has higher precedence. This breaking change causes subtle bugs during migration and makes code intent unclear.
|
||||
|
||||
The ESLint rule `vue/no-use-v-if-with-v-for` enforces this best practice.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Never place v-if and v-for on the same element
|
||||
- [ ] For filtering list items: use a computed property that filters the array
|
||||
- [ ] For hiding entire list: wrap with `<template v-if>` around the v-for
|
||||
- [ ] Enable eslint-plugin-vue rule `vue/no-use-v-if-with-v-for`
|
||||
|
||||
**Incorrect:**
|
||||
```html
|
||||
<!-- WRONG: v-if and v-for on same element - ambiguous precedence -->
|
||||
<template>
|
||||
<!-- Intent: show only active users -->
|
||||
<li v-for="user in users" v-if="user.isActive" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Hiding entire list conditionally -->
|
||||
<template>
|
||||
<li v-for="user in users" v-if="shouldShowList" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WRONG: Vue 3 precedence issue -->
|
||||
<template>
|
||||
<!-- In Vue 3, v-if runs FIRST, so 'user' is undefined! -->
|
||||
<li v-for="user in users" v-if="user.isActive" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
<!-- Error: Cannot read property 'isActive' of undefined -->
|
||||
</template>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- CORRECT: Filter with computed property -->
|
||||
<template>
|
||||
<li v-for="user in activeUsers" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps(['users'])
|
||||
|
||||
const activeUsers = computed(() =>
|
||||
props.users.filter(user => user.isActive)
|
||||
)
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: Wrap with <template v-if> for conditional list -->
|
||||
<template>
|
||||
<template v-if="shouldShowList">
|
||||
<li v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</template>
|
||||
</template>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- CORRECT: v-if inside the loop (per-item condition) -->
|
||||
<template>
|
||||
<ul>
|
||||
<template v-for="user in users" :key="user.id">
|
||||
<li v-if="user.isActive">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Vue 2 vs Vue 3 Precedence Change
|
||||
|
||||
```javascript
|
||||
// Vue 2: v-for evaluated first
|
||||
// <li v-for="user in users" v-if="user.isActive">
|
||||
// Equivalent to: users.forEach(user => { if (user.isActive) render(user) })
|
||||
|
||||
// Vue 3: v-if evaluated first
|
||||
// <li v-for="user in users" v-if="user.isActive">
|
||||
// Equivalent to: if (user.isActive) users.forEach(user => render(user))
|
||||
// Problem: 'user' doesn't exist yet when v-if runs!
|
||||
```
|
||||
|
||||
## Why Computed Properties Are Better
|
||||
|
||||
```javascript
|
||||
// Benefits of filtering via computed:
|
||||
// 1. Clear separation of concerns (logic vs template)
|
||||
// 2. Cached - only recalculates when dependencies change
|
||||
// 3. Reusable - can be used elsewhere in component
|
||||
// 4. Testable - can unit test the filtering logic
|
||||
// 5. No ambiguity about intent
|
||||
|
||||
const activeUsers = computed(() =>
|
||||
users.value.filter(u => u.isActive)
|
||||
)
|
||||
|
||||
// Can add more complex filtering
|
||||
const filteredUsers = computed(() =>
|
||||
users.value
|
||||
.filter(u => u.isActive)
|
||||
.filter(u => u.role === selectedRole.value)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
)
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Style Guide - Avoid v-if with v-for](https://vuejs.org/style-guide/rules-essential.html#avoid-v-if-with-v-for)
|
||||
- [Vue 3 Migration Guide - v-if vs v-for Precedence](https://v3-migration.vuejs.org/breaking-changes/v-if-v-for)
|
||||
- [ESLint Plugin Vue - no-use-v-if-with-v-for](https://eslint.vuejs.org/rules/no-use-v-if-with-v-for)
|
||||
@@ -0,0 +1,157 @@
|
||||
---
|
||||
title: Return Stable Object References from Computed Properties
|
||||
impact: MEDIUM
|
||||
impactDescription: Computed properties returning new objects trigger effects even when values haven't meaningfully changed
|
||||
type: efficiency
|
||||
tags: [vue3, computed, performance, reactivity, vue3.4]
|
||||
---
|
||||
|
||||
# Return Stable Object References from Computed Properties
|
||||
|
||||
**Impact: MEDIUM** - In Vue 3.4+, computed properties only trigger effects when their value changes. However, if a computed returns a new object each time, Vue cannot detect that the values inside are the same. This causes unnecessary effect re-runs.
|
||||
|
||||
For primitive values, Vue 3.4+ handles this automatically. For objects, manually compare and return the previous value when nothing meaningful has changed.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] For computed properties returning primitives, Vue 3.4+ handles stability automatically
|
||||
- [ ] For computed properties returning objects, compare with previous value and return old reference if unchanged
|
||||
- [ ] Always perform the full computation before comparing (to track dependencies correctly)
|
||||
- [ ] Consider if you really need to return an object, or if primitives would suffice
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed, watchEffect } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
|
||||
// BAD: Returns new object every time, always triggers effects
|
||||
const stats = computed(() => {
|
||||
return {
|
||||
isEven: count.value % 2 === 0,
|
||||
doubleValue: count.value * 2
|
||||
}
|
||||
})
|
||||
|
||||
watchEffect(() => {
|
||||
console.log('Stats changed:', stats.value)
|
||||
// Logs on EVERY count change, even when isEven hasn't changed
|
||||
// count: 0 -> 2 -> 4: isEven is always true, but effect runs each time
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<script setup>
|
||||
import { ref, computed, watchEffect } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
|
||||
// GOOD (Vue 3.4+): Primitive computed - automatic stability
|
||||
const isEven = computed(() => count.value % 2 === 0)
|
||||
|
||||
watchEffect(() => {
|
||||
console.log('isEven:', isEven.value)
|
||||
// Only logs when isEven actually changes (0, 2, 4 won't re-trigger)
|
||||
})
|
||||
|
||||
// GOOD (Vue 3.4+): Manual comparison for object returns
|
||||
const stats = computed((oldValue) => {
|
||||
// Step 1: Always compute the new value first (to track dependencies)
|
||||
const newValue = {
|
||||
isEven: count.value % 2 === 0,
|
||||
category: count.value < 10 ? 'small' : 'large'
|
||||
}
|
||||
|
||||
// Step 2: Compare with previous value
|
||||
if (oldValue &&
|
||||
oldValue.isEven === newValue.isEven &&
|
||||
oldValue.category === newValue.category) {
|
||||
return oldValue // Return old reference - no effect triggers
|
||||
}
|
||||
|
||||
return newValue
|
||||
})
|
||||
|
||||
watchEffect(() => {
|
||||
console.log('Stats changed:', stats.value)
|
||||
// Now only logs when isEven or category actually changes
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Primitive vs Object Computed Behavior (Vue 3.4+)
|
||||
|
||||
```javascript
|
||||
import { ref, computed, watchEffect } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
|
||||
// PRIMITIVE: Vue automatically detects value hasn't changed
|
||||
const isEven = computed(() => count.value % 2 === 0)
|
||||
|
||||
watchEffect(() => console.log(isEven.value)) // true
|
||||
|
||||
count.value = 2 // isEven still true - NO log
|
||||
count.value = 4 // isEven still true - NO log
|
||||
count.value = 3 // isEven now false - logs: false
|
||||
|
||||
// OBJECT: New reference every time (without manual comparison)
|
||||
const obj = computed(() => ({ isEven: count.value % 2 === 0 }))
|
||||
|
||||
watchEffect(() => console.log(obj.value)) // { isEven: true }
|
||||
|
||||
count.value = 2 // Logs again! New object reference
|
||||
count.value = 4 // Logs again! New object reference
|
||||
```
|
||||
|
||||
## Advanced: Deep Object Comparison
|
||||
|
||||
```javascript
|
||||
import { ref, computed } from 'vue'
|
||||
import { isEqual } from 'lodash-es' // For deep comparison
|
||||
|
||||
const filters = ref({ category: 'all', sortBy: 'date', page: 1 })
|
||||
|
||||
// For complex objects, use deep comparison
|
||||
const activeFilters = computed((oldValue) => {
|
||||
const newValue = {
|
||||
...filters.value,
|
||||
hasFilters: filters.value.category !== 'all' || filters.value.sortBy !== 'date'
|
||||
}
|
||||
|
||||
// Deep compare for complex objects
|
||||
if (oldValue && isEqual(oldValue, newValue)) {
|
||||
return oldValue
|
||||
}
|
||||
|
||||
return newValue
|
||||
})
|
||||
```
|
||||
|
||||
## Important: Always Compute Before Comparing
|
||||
|
||||
```javascript
|
||||
// BAD: Early return prevents dependency tracking
|
||||
const optimized = computed((oldValue) => {
|
||||
if (oldValue && someCondition) {
|
||||
return oldValue // Dependencies not tracked!
|
||||
}
|
||||
return computeExpensiveValue()
|
||||
})
|
||||
|
||||
// GOOD: Compute first, then compare
|
||||
const optimized = computed((oldValue) => {
|
||||
const newValue = computeExpensiveValue() // Always track dependencies
|
||||
if (oldValue && newValue === oldValue) {
|
||||
return oldValue
|
||||
}
|
||||
return newValue
|
||||
})
|
||||
```
|
||||
|
||||
## Reference
|
||||
- [Vue.js Performance - Computed Stability](https://vuejs.org/guide/best-practices/performance.html#computed-stability)
|
||||
- [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html)
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
title: Keep Props Stable to Minimize Child Re-renders
|
||||
impact: HIGH
|
||||
impactDescription: Passing changing props to list items causes ALL children to re-render unnecessarily
|
||||
type: efficiency
|
||||
tags: [vue3, performance, props, v-for, re-renders, optimization]
|
||||
---
|
||||
|
||||
# Keep Props Stable to Minimize Child Re-renders
|
||||
|
||||
**Impact: HIGH** - When props passed to child components change, Vue must re-render those components. Passing derived values like `activeId` to every list item causes all items to re-render when activeId changes, even if only one item's active state actually changed.
|
||||
|
||||
Move comparison logic to the parent and pass the boolean result instead. This is one of the most impactful update performance optimizations in Vue.
|
||||
|
||||
## Task Checklist
|
||||
|
||||
- [ ] Avoid passing parent-level state that all children compare against (like `activeId`)
|
||||
- [ ] Pre-compute derived boolean props in the parent (like `:active="item.id === activeId"`)
|
||||
- [ ] Profile re-renders using Vue DevTools to identify prop stability issues
|
||||
- [ ] Consider this pattern especially critical for large lists
|
||||
|
||||
**Incorrect:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- BAD: activeId changes -> ALL 100 ListItems re-render -->
|
||||
<ListItem
|
||||
v-for="item in list"
|
||||
:key="item.id"
|
||||
:id="item.id"
|
||||
:active-id="activeId"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const list = ref([/* 100 items */])
|
||||
const activeId = ref(null)
|
||||
|
||||
// When activeId changes from 1 to 2:
|
||||
// - ListItem 1 needs to re-render (was active, now not)
|
||||
// - ListItem 2 needs to re-render (was not active, now active)
|
||||
// - All other 98 ListItems ALSO re-render because activeId prop changed!
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ListItem.vue - receives activeId and compares internally -->
|
||||
<template>
|
||||
<div :class="{ active: id === activeId }">
|
||||
{{ id }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineProps({
|
||||
id: Number,
|
||||
activeId: Number // This prop changes for ALL items
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```vue
|
||||
<template>
|
||||
<!-- GOOD: Only items whose :active actually changed will re-render -->
|
||||
<ListItem
|
||||
v-for="item in list"
|
||||
:key="item.id"
|
||||
:id="item.id"
|
||||
:active="item.id === activeId"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const list = ref([/* 100 items */])
|
||||
const activeId = ref(null)
|
||||
|
||||
// When activeId changes from 1 to 2:
|
||||
// - ListItem 1: :active changed from true to false -> re-renders
|
||||
// - ListItem 2: :active changed from false to true -> re-renders
|
||||
// - All other 98 ListItems: :active is still false -> NO re-render!
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- ListItem.vue - receives pre-computed boolean -->
|
||||
<template>
|
||||
<div :class="{ active }">
|
||||
{{ id }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineProps({
|
||||
id: Number,
|
||||
active: Boolean // This only changes for items that truly changed
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Common Patterns That Cause Prop Instability
|
||||
|
||||
```vue
|
||||
<!-- BAD: Passing index that could shift -->
|
||||
<Item
|
||||
v-for="(item, index) in items"
|
||||
:key="item.id"
|
||||
:index="index"
|
||||
:total="items.length" <!-- Changes when list changes -->
|
||||
/>
|
||||
|
||||
<!-- BAD: Passing entire selection set -->
|
||||
<Item
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
:selected-ids="selectedIds" <!-- All items re-render on any selection -->
|
||||
/>
|
||||
|
||||
<!-- GOOD: Pre-compute the boolean -->
|
||||
<Item
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
:selected="selectedIds.includes(item.id)"
|
||||
/>
|
||||
```
|
||||
|
||||
## Performance Impact Example
|
||||
|
||||
| Scenario | Props Changed | Components Re-rendered |
|
||||
|----------|---------------|------------------------|
|
||||
| 100 items, pass `activeId` | 100 | 100 (all) |
|
||||
| 100 items, pass `:active` boolean | 2 | 2 (only changed) |
|
||||
| 1000 items, pass `activeId` | 1000 | 1000 (all) |
|
||||
| 1000 items, pass `:active` boolean | 2 | 2 (only changed) |
|
||||
|
||||
## Reference
|
||||
- [Vue.js Performance - Props Stability](https://vuejs.org/guide/best-practices/performance.html#props-stability)
|
||||
@@ -0,0 +1,109 @@
|
||||
# Use Global Properties Sparingly in Plugins
|
||||
|
||||
## Rule
|
||||
|
||||
When using `app.config.globalProperties` in Vue plugins, use them sparingly and with clear naming conventions. Excessive global properties lead to confusion, naming conflicts, and debugging difficulties.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
1. **Implicit dependencies**: Global properties make component dependencies invisible, making code harder to understand and maintain.
|
||||
|
||||
2. **Naming collisions**: Multiple plugins may try to use the same property name (e.g., `$http`, `$api`), causing silent overwrites.
|
||||
|
||||
3. **Debugging difficulty**: When issues arise, tracing back to which plugin provides a global property is challenging.
|
||||
|
||||
4. **IDE limitations**: Global properties may not have proper autocomplete or type checking without careful configuration.
|
||||
|
||||
5. **Testing complexity**: Global state is harder to mock and isolate in unit tests.
|
||||
|
||||
## Bad Practice
|
||||
|
||||
```typescript
|
||||
// Too many global properties from various plugins
|
||||
app.config.globalProperties.$http = axios
|
||||
app.config.globalProperties.$api = apiClient
|
||||
app.config.globalProperties.$auth = authService
|
||||
app.config.globalProperties.$translate = i18n.translate
|
||||
app.config.globalProperties.$format = formatters
|
||||
app.config.globalProperties.$utils = utilities
|
||||
app.config.globalProperties.$config = appConfig
|
||||
app.config.globalProperties.$logger = logger
|
||||
|
||||
// In component - where did all these come from?
|
||||
export default {
|
||||
mounted() {
|
||||
this.$logger.info('Mounted')
|
||||
const data = await this.$http.get(this.$config.apiUrl)
|
||||
this.$api.process(this.$utils.transform(data))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Good Practice
|
||||
|
||||
```typescript
|
||||
// Use provide/inject for most functionality
|
||||
export default {
|
||||
install(app, options) {
|
||||
// Provide services via injection
|
||||
app.provide('api', apiClient)
|
||||
app.provide('auth', authService)
|
||||
app.provide('i18n', i18n)
|
||||
|
||||
// Reserve globalProperties for truly global template helpers
|
||||
// that are used extensively in templates across the app
|
||||
app.config.globalProperties.$t = i18n.translate // Common convention
|
||||
}
|
||||
}
|
||||
|
||||
// In component - explicit dependencies
|
||||
<script setup>
|
||||
import { inject } from 'vue'
|
||||
|
||||
const api = inject('api')
|
||||
const auth = inject('auth')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- $t is acceptable for common template-only usage -->
|
||||
<h1>{{ $t('welcome') }}</h1>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
If you do use globalProperties:
|
||||
|
||||
1. **Use `$` prefix**: This is the Vue convention and avoids conflicts with component data/methods
|
||||
2. **Use unique prefixes for your library**: e.g., `$myLib_translate` for third-party plugins
|
||||
3. **Document all global properties**: Keep a central registry of what each plugin provides
|
||||
|
||||
```typescript
|
||||
// Good: namespaced to avoid conflicts
|
||||
app.config.globalProperties.$myPlugin = {
|
||||
translate: (key) => /* ... */,
|
||||
format: (value) => /* ... */
|
||||
}
|
||||
|
||||
// Usage
|
||||
{{ $myPlugin.translate('key') }}
|
||||
```
|
||||
|
||||
## Auditing Global Properties
|
||||
|
||||
You can inspect all global properties for debugging:
|
||||
|
||||
```typescript
|
||||
console.log(app.config.globalProperties)
|
||||
```
|
||||
|
||||
## When Global Properties Are Acceptable
|
||||
|
||||
1. **Template-only utilities** used very frequently (like `$t` for translations)
|
||||
2. **Legacy migration** when transitioning from Vue 2
|
||||
3. **Libraries that need Options API compatibility** (but prefer also providing inject)
|
||||
|
||||
## References
|
||||
|
||||
- [Vue.js Plugins Documentation](https://vuejs.org/guide/reusability/plugins.html)
|
||||
- [Vue.js Global Properties](https://vuejs.org/api/application.html#app-config-globalproperties)
|
||||
@@ -0,0 +1,124 @@
|
||||
# Install Plugins Before Mounting the App
|
||||
|
||||
## Rule
|
||||
|
||||
All plugins must be installed using `app.use()` BEFORE calling `app.mount()`. Installing plugins after the app is mounted can lead to reactivity issues, missing dependencies, and unexpected behavior.
|
||||
|
||||
## Why This Matters
|
||||
|
||||
1. **Hidden dependencies**: Components may render before plugins they depend on are available, causing runtime errors.
|
||||
|
||||
2. **Reactivity issues**: Late plugin installation can cause subtle reactivity problems where provided values aren't properly reactive.
|
||||
|
||||
3. **Initialization order**: Many plugins (like vue-router, pinia) need to set up state before any component renders.
|
||||
|
||||
4. **Ecosystem complexity**: Adding plugins after mount can cause issues with Vue's internal ecosystem and hydration in SSR scenarios.
|
||||
|
||||
## Bad Practice
|
||||
|
||||
```typescript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import i18nPlugin from './plugins/i18n'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// Mounting first - plugins not yet available!
|
||||
app.mount('#app')
|
||||
|
||||
// Installing after mount - TOO LATE!
|
||||
app.use(router)
|
||||
app.use(i18nPlugin, { locale: 'en' })
|
||||
```
|
||||
|
||||
## Good Practice
|
||||
|
||||
```typescript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { createPinia } from 'pinia'
|
||||
import i18nPlugin from './plugins/i18n'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// Install all plugins BEFORE mounting
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(i18nPlugin, { locale: 'en' })
|
||||
|
||||
// Mount LAST
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## Plugin Installation Order
|
||||
|
||||
The order of `app.use()` calls can matter when plugins depend on each other:
|
||||
|
||||
```typescript
|
||||
const app = createApp(App)
|
||||
|
||||
// 1. State management first (other plugins might need it)
|
||||
app.use(createPinia())
|
||||
|
||||
// 2. Router (may depend on state)
|
||||
app.use(router)
|
||||
|
||||
// 3. Other plugins (may depend on router or state)
|
||||
app.use(authPlugin)
|
||||
app.use(i18nPlugin, { locale: 'en' })
|
||||
|
||||
// 4. Mount last
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## Async Plugin Installation
|
||||
|
||||
If you need to perform async operations before mounting:
|
||||
|
||||
```typescript
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import { loadPlugins } from './plugins'
|
||||
|
||||
async function bootstrap() {
|
||||
const app = createApp(App)
|
||||
|
||||
// Await async plugin setup
|
||||
const i18nPlugin = await loadI18nMessages()
|
||||
|
||||
// Install all plugins
|
||||
app.use(i18nPlugin)
|
||||
|
||||
// Mount after everything is ready
|
||||
app.mount('#app')
|
||||
}
|
||||
|
||||
bootstrap()
|
||||
```
|
||||
|
||||
## Duplicate Installation Protection
|
||||
|
||||
Vue's `app.use()` automatically prevents duplicate plugin installation:
|
||||
|
||||
```typescript
|
||||
app.use(myPlugin)
|
||||
app.use(myPlugin) // This second call is ignored - no double installation
|
||||
|
||||
// This is handled internally by Vue, providing a safety net
|
||||
```
|
||||
|
||||
## Common Symptoms of Late Plugin Installation
|
||||
|
||||
- `inject()` returns `undefined` unexpectedly
|
||||
- Router navigation guards not firing
|
||||
- Store state not reactive
|
||||
- Template errors about undefined global properties
|
||||
- Hydration mismatches in SSR
|
||||
|
||||
## References
|
||||
|
||||
- [Vue.js Plugins Documentation](https://vuejs.org/guide/reusability/plugins.html)
|
||||
- [Vue.js Application API](https://vuejs.org/api/application.html)
|
||||
- [Vue 3 Migration Guide - Global API](https://v3-migration.vuejs.org/breaking-changes/global-api.html)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user