You’re browsing the documentation for v2.x and earlier. For v3.x, click here.
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.
Soon, we’ll also provide tips for enforcement. Sometimes you’ll simply have to be disciplined, but wherever possible, we’ll try to show you how to use ESLint and other automated processes to make enforcement simpler.
Finally, we’ve split rules into four categories:
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.
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:
- train your brain to more easily parse most of the community code you encounter
- be able to copy and paste most community code examples without modification
- often find new hires are already accustomed to your preferred coding style, at least in regards to Vue
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.
Component names should always be multi-word, except for root
App components, and built-in components provided by Vue, such as
This prevents conflicts with existing and future HTML elements, since all HTML elements are a single word.
data must be a function.
When using the
data property on a component (i.e. anywhere except on
new Vue), the value must be a function that returns an object.
When the value of
data is an object, it’s shared across all instances of a component. Imagine, for example, a
TodoList component with this data:
We might want to reuse this component, allowing users to maintain multiple lists (e.g. for shopping, wishlists, daily chores, etc). There’s a problem though. Since every instance of the component references the same data object, changing the title of one list will also change the title of every other list. The same is true for adding/editing/deleting a todo.
Prop definitions should be as detailed as possible.
In committed code, prop definitions should always be as detailed as possible, specifying at least type(s).
Detailed prop definitions 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.
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 in animations.
Let’s say you have a list of todos:
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
<transition-group> to animate list sorting, or maintain focus if the rendered element is an
<input>. 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.
v-if on the same element as
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
userswith a new computed property that returns your filtered list (e.g.
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-ifto a container element (e.g.
When Vue processes directives,
v-for has a higher priority than
v-if, so that this template:
Will be evaluated similar to:
So even if we only render elements for a small fraction of users, we have to iterate over the entire list every time we re-render, whether or not the set of active users has changed.
By iterating over a computed property instead, like this:
We get the following benefits:
- The filtered list will only be re-evaluated if there are relevant changes to the
usersarray, making filtering much more efficient.
v-for="user in activeUsers", we only iterate over active users during render, making rendering much more efficient.
- Logic is now decoupled from the presentation layer, making maintenance (change/extension of logic) much easier.
We get similar benefits from updating:
By moving the
v-if to a container element, we’re no longer checking
shouldShowUsers for every user in the list. Instead, we check it once and don’t even evaluate the
shouldShowUsers is false.
For applications, styles in a top-level
App component and in layout components may be global, but all other components should always be scoped.
This is only relevant for single-file components. It does not require that the
scoped attribute be used. Scoping could be through CSS modules, a class-based strategy such as BEM, or another library/convention.
Component libraries, however, should prefer a class-based strategy instead of using the
This makes overriding internal styles easier, with human-readable class names that don’t have too high specificity, but are still very unlikely to result in a conflict.
If you are developing a large project, working with other developers, or sometimes include 3rd-party HTML/CSS (e.g. from Auth0), consistent scoping will ensure that your styles only apply to the components they are meant for.
scoped attribute, using unique class names can help ensure that 3rd-party CSS does not apply to your own HTML. For example, many projects use the
icon class names, so even if not using a strategy such as BEM, adding an app-specific and/or component-specific prefix (e.g.
ButtonClose-icon) can provide some protection.
Use module scoping to keep private functions inaccessible from the outside. If that’s not possible, always use the
$_ prefix for custom private properties in a plugin, mixin, etc that should not be considered public API. Then to avoid conflicts with code by other authors, also include a named scope (e.g.
Vue uses the
_ prefix to define its own private properties, so using the same prefix (e.g.
_update) risks overwriting an instance property. Even if you check and Vue is not currently using a particular property name, there is no guarantee a conflict won’t arise in a later version.
As for the
$ prefix, its purpose within the Vue ecosystem is special instance properties that are exposed to the user, so using it for private properties would not be appropriate.
Instead, we recommend combining the two prefixes into
$_, as a convention for user-defined private properties that guarantee no conflicts with Vue.
Whenever a build system is available to concatenate files, each component should be in its own file.
This helps you to more quickly find a component when you need to edit it or review how to use it.
Filenames of single-file components should either be always PascalCase or always kebab-case.
PascalCase works best with autocompletion in code editors, as it’s consistent with how we reference components in JS(X) and templates, wherever possible. However, mixed case filenames can sometimes create issues on case-insensitive file systems, which is why kebab-case is also perfectly acceptable.
Base components (a.k.a. presentational, dumb, or pure components) that apply app-specific styling and conventions should all begin with a specific prefix, such as
These components lay the foundation for consistent styling and behavior in your application. They may only contain:
- HTML elements,
- other base components, and
- 3rd-party UI components.
But they’ll never contain global state (e.g. from a Vuex store).
Their names often include the name of an element they wrap (e.g.
BaseTable), unless no element exists for their specific purpose (e.g.
BaseIcon). If you build similar components for a more specific context, they will almost always consume these components (e.g.
BaseButton may be used in
Some advantages of this convention:
When organized alphabetically in editors, your app’s base components are all listed together, making them easier to identify.
Since component names should always be multi-word, this convention prevents you from having to choose an arbitrary prefix for simple component wrappers (e.g.
Components that should only ever have a single active instance should begin with the
The prefix, to denote that there can be only one.
This does not mean the component is only used in a single page, but it will only be used once per page. These components never accept any props, since they are specific to your app, not their context within your app. If you find the need to add props, it’s a good indication that this is actually a reusable component that is only used once per page for now.
Child components that are tightly coupled with their parent should include the parent component name as a prefix.
If a component only makes sense in the context of a single parent component, that relationship should be evident in its name. Since editors typically organize files alphabetically, this also keeps these related files next to each other.
You might be tempted to solve this problem by nesting child components in directories named after their parent. For example:
This isn’t recommended, as it results in:
- Many files with similar names, making rapid file switching in code editors more difficult.
- Many nested sub-directories, which increases the time it takes to browse components in an editor’s sidebar.
Component names should start with the highest-level (often most general) words and end with descriptive modifying words.
You may be wondering:
“Why would we force component names to use less natural language?”
In natural English, adjectives and other descriptors do typically appear before the nouns, while exceptions require connector words. For example:
- Coffee with milk
- Soup of the day
- Visitor to the museum
You can definitely include these connector words in component names if you’d like, but the order is still important.
Also note that what’s considered “highest-level” will be contextual to your app. For example, imagine an app with a search form. It may include components like this one:
As you might notice, it’s quite difficult to see which components are specific to the search. Now let’s rename the components according to the rule:
Since editors typically organize files alphabetically, all the important relationships between components are now evident at a glance.
You might be tempted to solve this problem differently, nesting all the search components under a “search” directory, then all the settings components under a “settings” directory. We only recommend considering this approach in very large apps (e.g. 100+ components), for these reasons:
- It generally takes more time to navigate through nested sub-directories, than scrolling through a single
- Name conflicts (e.g. multiple
ButtonDelete.vuecomponents) make it more difficult to quickly navigate to a specific component in a code editor.
- Refactoring becomes more difficult, because find-and-replace often isn’t sufficient to update relative references to a moved component.
Components that self-close communicate that they not only have no content, but are meant to have no content. It’s the difference between a blank page in a book and one labeled “This page intentionally left blank.” Your code is also cleaner without the unnecessary closing tag.
Unfortunately, HTML doesn’t allow custom elements to be self-closing - only official “void” elements. That’s why the strategy is only possible when Vue’s template compiler can reach the template before the DOM, then serve the DOM spec-compliant HTML.
In most projects, component names should always be PascalCase in single-file components and string templates - but kebab-case in DOM templates.
PascalCase has a few advantages over kebab-case:
<MyComponent>is more visually distinct from a single-word HTML element than
<my-component>, because there are two character differences (the two capitals), rather than just one (a hyphen).
- If you use any non-Vue custom elements in your templates, such as a web component, PascalCase ensures that your Vue components remain distinctly visible.
Unfortunately, due to HTML’s case insensitivity, DOM templates must still use kebab-case.
Also note that if you’ve already invested heavily in kebab-case, consistency with HTML conventions and being able to use the same casing across all your projects may be more important than the advantages listed above. In those cases, using kebab-case everywhere is also acceptable.
Component names in JS/JSX should always be PascalCase, though they may be kebab-case inside strings for simpler applications that only use global component registration through
However, for applications that use only global component definitions via
Vue.component, we recommend kebab-case instead. The reasons are:
- These applications always include many in-DOM templates, where kebab-case must be used.
Component names should prefer full words over abbreviations.
The autocompletion in editors make the cost of writing longer names very low, while the clarity they provide is invaluable. Uncommon abbreviations, in particular, should always be avoided.
Prop names should always use camelCase during declaration, but kebab-case in templates and JSX.
Elements with multiple attributes should span multiple lines, with one attribute per line.
Component templates should only include simple expressions, with more complex expressions refactored into computed properties or methods.
Complex expressions in your templates make them less declarative. We should strive to describe what should appear, not how we’re computing that value. Computed properties and methods also allow the code to be reused.
Complex computed properties should be split into as many simpler properties as possible.
Simpler, well-named computed properties are:
Easier to test
When each computed property contains only a very simple expression, with very few dependencies, it’s much easier to write tests confirming that it works correctly.
Easier to read
Simplifying computed properties forces you to give each value a descriptive name, even if it’s not reused. This makes it much easier for other developers (and future you) to focus on the code they care about and figure out what’s going on.
More adaptable to changing requirements
Any value that can be named might be useful to the view. For example, we might decide to display a message telling the user how much money they saved. We might also decide to calculate sales tax, but perhaps display it separately, rather than as part of the final price.
Small, focused computed properties make fewer assumptions about how information will be used, so require less refactoring as requirements change.
Non-empty HTML attribute values should always be inside quotes (single or double, whichever is not used in JS).
While attribute values without any spaces are not required to have quotes in HTML, this practice often leads to avoiding spaces, making attribute values less readable.
Directive shorthands (
v-slot) should be used always or never.
Component/instance options should be ordered consistently.
This is the default order we recommend for component options. They’re split into categories, so you’ll know where to add new properties from plugins.
Side Effects (triggers effects outside the component)
Global Awareness (requires knowledge beyond the component)
Component Type (changes the type of the component)
Template Modifiers (changes the way templates are compiled)
Template Dependencies (assets used in the template)
Composition (merges properties into the options)
Interface (the interface to the component)
Local State (local reactive properties)
Events (callbacks triggered by reactive events)
- Lifecycle Events (in the order they are called)
Non-Reactive Properties (instance properties independent of the reactivity system)
Rendering (the declarative description of the component output)
The attributes of elements (including components) should be ordered consistently.
This is the default order we recommend for component options. They’re split into categories, so you’ll know where to add custom attributes and directives.
Definition (provides the component options)
List Rendering (creates multiple variations of the same element)
Conditionals (whether the element is rendered/shown)
Render Modifiers (changes the way the element renders)
Global Awareness (requires knowledge beyond the component)
Unique Attributes (attributes that require unique values)
Two-Way Binding (combining binding and events)
Other Attributes (all unspecified bound & unbound attributes)
Events (component event listeners)
Content (overrides the content of the element)
You may want to add one empty line between multi-line properties, particularly if the options can no longer fit on your screen without scrolling.
When components begin to feel cramped or difficult to read, adding spaces between multi-line properties can make them easier to skim again. In some editors, such as Vim, formatting options like this can also make them easier to navigate with the keyboard.
Single-file components should always order
<style> tags consistently, with
<style> last, because at least one of the other two is always necessary.
It’s usually best to use
v-else, if they are the same element type (e.g. both
By default, Vue updates the DOM as efficiently as possible. That means when switching between elements of the same type, it simply patches the existing element, rather than removing it and adding a new one in its place. This can have unintended consequences if these elements should not actually be considered the same.
Element selectors should be avoided with
Prefer class selectors over element selectors in
scoped styles, because large numbers of element selectors are slow.
To scope styles, Vue adds a unique attribute to component elements, such as
data-v-f3f3eg9. Then selectors are modified so that only matching elements with this attribute are selected (e.g.
The problem is that large numbers of element-attribute selectors (e.g.
button[data-v-f3f3eg9]) will be considerably slower than class-attribute selectors (e.g.
.btn-close[data-v-f3f3eg9]), so class selectors should be preferred whenever possible.
Props and events should be preferred for parent-child component communication, instead of
this.$parent or mutating props.
An ideal Vue application is props down, events up. Sticking to this convention makes your components much easier to understand. However, there are edge cases where prop mutation or
this.$parent can simplify two components that are already deeply coupled.
The problem is, there are also many simple cases where these patterns may offer convenience. Beware: do not be seduced into trading simplicity (being able to understand the flow of your state) for short-term convenience (writing less code).
Vuex should be preferred for global state management, instead of
this.$root or a global event bus.
Managing state on
this.$root and/or using a global event bus can be convenient for very simple cases, but it is not appropriate for most applications.
Vuex is the official flux-like implementation for Vue, and offers not only a central place to manage state, but also tools for organizing, tracking, and debugging state changes. It integrates well in the Vue ecosystem (including full Vue DevTools support).