From 4f4f1b9b6c292e2a65aa993b51fdf3ae7f6f66cd Mon Sep 17 00:00:00 2001 From: Haoqun Jiang Date: Thu, 19 Mar 2026 22:58:20 +0900 Subject: [PATCH 1/8] revamp the essential style guide and mark others as legacy --- src/style-guide/index.md | 36 +- src/style-guide/rules-essential.md | 327 ++++++------------ src/style-guide/rules-recommended.md | 6 +- src/style-guide/rules-strongly-recommended.md | 6 +- src/style-guide/rules-use-with-caution.md | 6 +- 5 files changed, 132 insertions(+), 249 deletions(-) diff --git a/src/style-guide/index.md b/src/style-guide/index.md index 8f7b747f60..865296cbe4 100644 --- a/src/style-guide/index.md +++ b/src/style-guide/index.md @@ -4,42 +4,44 @@ outline: deep # Style Guide {#style-guide} -::: warning Note -This Vue.js Style Guide is outdated and needs to be reviewed. If you have any questions or suggestions, please [open an issue](https://github.com/vuejs/docs/issues/new). +::: warning Status +This section is under active revision. Priority A: Essential is currently the maintained section of the guide. Priority B, C, and D are retained as legacy reference content. ::: -This is the official style guide for Vue-specific code. If you use Vue in a project, it's a great reference to avoid errors, bikeshedding, and anti-patterns. However, we don't believe that any style guide is ideal for all teams or projects, so mindful deviations are encouraged based on past experience, the surrounding tech stack, and personal values. +This is the official style guide for Vue-specific code. It is meant to help teams make sound architectural, semantic, and maintainability decisions in modern Vue applications. However, no style guide is ideal for every team or project, so mindful deviations are still encouraged when they are deliberate and well understood. -For the most part, we also avoid suggestions about JavaScript or HTML in general. We don't mind whether you use semicolons or trailing commas. We don't mind whether your HTML uses single-quotes or double-quotes for attribute values. Some exceptions will exist however, where we've found that a particular pattern is helpful in the context of Vue. +This guide focuses on a small set of human-facing Vue rules. It is not intended to mirror every rule that lint tooling may enforce. Tools such as [eslint-plugin-vue](https://eslint.vuejs.org/), formatters, and other static analysis can still cover broader mechanical correctness and consistency checks. -Finally, we've split rules into four categories: +For the most part, we avoid suggestions about JavaScript or HTML in general. We do not try to settle choices like semicolons, trailing commas, or quote style unless they become specifically important in the context of Vue. + +## How to use this guide {#how-to-use-this-guide} + +- Start with the [essential rules](./rules-essential). They are the primary maintained part of this guide and focus on component contracts, explicit data flow, component boundaries, and the Vue mental model. +- Treat Priority B, C, and D as legacy reference pages. They may still contain useful conventions, but they are not part of the current maintained scope. +- If your team uses [eslint-plugin-vue](https://eslint.vuejs.org/), expect tooling to enforce additional syntax, correctness, and consistency rules that are not all repeated here. ## Rule Categories {#rule-categories} -### Priority A: Essential (Error Prevention) {#priority-a-essential-error-prevention} +### Priority A: Essential (Maintained) {#priority-a-essential-error-prevention} -These rules help prevent errors, so learn and abide by them at all costs. Exceptions may exist, but should be very rare and only be made by those with expert knowledge of both JavaScript and Vue. +These rules focus on component contracts, explicit data flow, component boundaries, and the Vue mental model. They are written to guide human decisions, not to duplicate every lint rule. - [See all priority A rules](./rules-essential) -### Priority B: Strongly Recommended {#priority-b-strongly-recommended} +### Priority B: Strongly Recommended (Legacy Reference) {#priority-b-strongly-recommended} -These rules have been found to improve readability and/or developer experience in most projects. Your code will still run if you violate them, but violations should be rare and well-justified. +This page is preserved for historical reference. Its recommendations may still be useful, but they are not part of the current maintained scope. - [See all priority B rules](./rules-strongly-recommended) -### Priority C: Recommended {#priority-c-recommended} - -Where multiple, equally good options exist, an arbitrary choice can be made to ensure consistency. In these rules, we describe each acceptable option and suggest a default choice. That means you can feel free to make a different choice in your own codebase, as long as you're consistent and have a good reason. Please do have a good reason though! By adapting to the community standard, you will: +### Priority C: Recommended (Legacy Reference) {#priority-c-recommended} -1. Train your brain to more easily parse most of the community code you encounter -2. Be able to copy and paste most community code examples without modification -3. Often find new hires are already accustomed to your preferred coding style, at least in regards to Vue +This page is also preserved as legacy reference content. It may help teams that want additional conventions, but it is not part of the current maintained scope. - [See all priority C rules](./rules-recommended) -### Priority D: Use with Caution {#priority-d-use-with-caution} +### Priority D: Use with Caution (Legacy Reference) {#priority-d-use-with-caution} -Some features of Vue exist to accommodate rare edge cases or smoother migrations from a legacy code base. When overused however, they can make your code more difficult to maintain or even become a source of bugs. These rules shine a light on potentially risky features, describing when and why they should be avoided. +This page remains available as historical guidance on risky patterns, but it is not part of the current maintained scope. - [See all priority D rules](./rules-use-with-caution) diff --git a/src/style-guide/rules-essential.md b/src/style-guide/rules-essential.md index 0872dc499e..e21e27707f 100644 --- a/src/style-guide/rules-essential.md +++ b/src/style-guide/rules-essential.md @@ -1,51 +1,12 @@ # Priority A Rules: Essential {#priority-a-rules-essential} -::: warning Note -This Vue.js Style Guide is outdated and needs to be reviewed. If you have any questions or suggestions, please [open an issue](https://github.com/vuejs/docs/issues/new). -::: - -These rules help prevent errors, so learn and abide by them at all costs. Exceptions may exist, but should be very rare and only be made by those with expert knowledge of both JavaScript and Vue. - -## Use multi-word component names {#use-multi-word-component-names} - -User component names should always be multi-word, except for root `App` components. This [prevents conflicts](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name) with existing and future HTML elements, since all HTML elements are a single word. - -
-

Bad

- -```vue-html - - - - - -``` - -
- -
-

Good

- -```vue-html - - - - - -``` - -
- ## Use detailed prop definitions {#use-detailed-prop-definitions} -In committed code, prop definitions should always be as detailed as possible, specifying at least type(s). +Treat props as part of a component's public contract, and define them as explicitly as practical. -::: details Detailed Explanation -Detailed [prop definitions](/guide/components/props#prop-validation) have two advantages: - -- They document the API of the component, so that it's easy to see how the component is meant to be used. -- In development, Vue will warn you if a component is ever provided incorrectly formatted props, helping you catch potential sources of error. - ::: +::: details Why this matters +Detailed [prop definitions](/guide/components/props#prop-validation) make a component's API easier to understand, easier to use correctly, and easier to change safely. +:::
@@ -114,7 +75,6 @@ const props = defineProps({ ```js // Even better! - const props = defineProps({ status: { type: String, @@ -133,67 +93,28 @@ const props = defineProps({
-## Use keyed `v-for` {#use-keyed-v-for} - -`key` with `v-for` is _always_ required on components, in order to maintain internal component state down the subtree. Even for elements though, it's a good practice to maintain predictable behavior, such as [object constancy](https://bost.ocks.org/mike/constancy/) in animations. +**Notes** -::: details Detailed Explanation -Let's say you have a list of todos: +- In TypeScript, a type-based `defineProps()` declaration is equally acceptable if it expresses the contract clearly. +- Array syntax may be acceptable while prototyping, but committed components should define a real contract. -
+## Declare emitted events {#declare-emitted-events} -```js -data() { - return { - todos: [ - { - id: 1, - text: 'Learn to use v-for' - }, - { - id: 2, - text: 'Learn to use key' - } - ] - } -} -``` +Treat emitted events as part of a component's public contract, and declare them explicitly. -
- -
- -```js -const todos = ref([ - { - id: 1, - text: 'Learn to use v-for' - }, - { - id: 2, - text: 'Learn to use key' - } -]) -``` - -
- -Then you sort them alphabetically. When updating the DOM, Vue will optimize rendering to perform the cheapest DOM mutations possible. That might mean deleting the first todo element, then adding it again at the end of the list. - -The problem is, there are cases where it's important not to delete elements that will remain in the DOM. For example, you may want to use `` to animate list sorting, or maintain focus if the rendered element is an ``. In these cases, adding a unique key for each item (e.g. `:key="todo.id"`) will tell Vue how to behave more predictably. - -In our experience, it's better to _always_ add a unique key, so that you and your team simply never have to worry about these edge cases. Then in the rare, performance-critical scenarios where object constancy isn't necessary, you can make a conscious exception. +::: details Why this matters +Explicit [event declarations](/guide/components/events) document how a component communicates outward and make parent-child interactions easier to follow. :::

Bad

-```vue-html -
    -
  • - {{ todo.text }} -
  • -
+```js +const emit = defineEmits() + +function submit() { + emit('submit', { email: form.email }) +} ```
@@ -201,108 +122,53 @@ In our experience, it's better to _always_ add a unique key, so that you and you

Good

-```vue-html -
    -
  • - {{ todo.text }} -
  • -
-``` - -
- -## Avoid `v-if` with `v-for` {#avoid-v-if-with-v-for} - -**Never use `v-if` on the same element as `v-for`.** - -There are two common cases where this can be tempting: - -- To filter items in a list (e.g. `v-for="user in users" v-if="user.isActive"`). In these cases, replace `users` with a new computed property that returns your filtered list (e.g. `activeUsers`). - -- To avoid rendering a list if it should be hidden (e.g. `v-for="user in users" v-if="shouldShowUsers"`). In these cases, move the `v-if` to a container element (e.g. `ul`, `ol`). - -::: details Detailed Explanation -When Vue processes directives, `v-if` has a higher priority than `v-for`, so that this template: +```js +const emit = defineEmits({ + submit: ({ email }) => typeof email === 'string' +}) -```vue-html - +function submit() { + emit('submit', { email: form.email }) +} ``` -Will throw an error, because the `v-if` directive will be evaluated first and the iteration variable `user` does not exist at this moment. - -This could be fixed by iterating over a computed property instead, like this: - -
+```ts +const emit = defineEmits<{ + (e: 'submit', payload: { email: string }): void +}>() -```js -computed: { - activeUsers() { - return this.users.filter(user => user.isActive) - } +function submit() { + emit('submit', { email: form.email }) } ```
-
+**Notes** -```js -const activeUsers = computed(() => { - return users.filter((user) => user.isActive) -}) -``` +- An array of event names is acceptable when payload validation would add no real value. +- In TypeScript, prefer a typed `defineEmits()` declaration so the event contract is checked by the type system as well as documented in the component. +- If runtime payload validation is also useful, use the object syntax. -
+## Keep parent-child data flow explicit {#keep-parent-child-data-flow-explicit} -```vue-html - -``` - -Alternatively, we can use a `