Option 1: Disable globally
To disable the rule in all files (even those in src/components
):
// <projectRoot>/.eslintrc.js
module.exports = {
⋮
rules: {
'vue/multi-word-component-names': 0,
},
}
Option 2: overrides
in ESLint config for src/views/
To disable the rule only for src/views/**/*.vue
, specify an overrides
config:
// <projectRoot>/.eslintrc.js
module.exports = {
⋮
overrides: [
{
files: ['src/views/**/*.vue'],
rules: {
'vue/multi-word-component-names': 0,
},
},
],
}
Note: If using VS Code with the ESLint Extension, restarting the ESLint Server (through Command Palette’s >ESLint: Restart ESLint Server
command) or restarting the IDE might be needed to reload the configuration.
Option 3: Directory-level config for src/views/
It’s also possible to disable the rule for src/views/**/*.vue
with an .eslintrc.js
file in that directory:
// <projectRoot>/src/views/.eslintrc.js
module.exports = {
rules: {
'vue/multi-word-component-names': 0,
},
}
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.
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.
Finally, we’ve split rules into four categories:
# Rule Categories
# Priority A: Essential
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.
# 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.
# 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:
- 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
# 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.
# Priority A Rules: Essential
# Multi-word component names essential
Component names should always be multi-word, except for root App
components, and built-in components provided by Vue, such as <transition>
or <component>
.
This prevents conflicts (opens new window) with existing and future HTML elements, since all HTML elements are a single word.
Bad
app.component('todo', {
// ...
})
1
2
3
export default {
name: 'Todo',
// ...
}
1
2
3
4
Good
app.component('todo-item', {
// ...
})
1
2
3
export default {
name: 'TodoItem',
// ...
}
1
2
3
4
# Prop definitions essential
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 Explanation
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.
Bad
// This is only OK when prototyping
props: ['status']
1
2
Good
props: {
status: String
}
1
2
3
// Even better!
props: {
status: {
type: String,
required: true,
validator: value => {
return [
'syncing',
'synced',
'version-conflict',
'error'
].includes(value)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Keyed v-for
essential
Always use key
with 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 (opens new window) in animations.
Detailed Explanation
Let’s say you have a list of todos:
data() {
return {
todos: [
{
id: 1,
text: 'Learn to use v-for'
},
{
id: 2,
text: 'Learn to use key'
}
]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.
Bad
<ul>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ul>
1
2
3
4
5
Good
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
1
2
3
4
5
6
7
8
# Avoid v-if
with v-for
essential
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, replaceusers
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 thev-if
to a container element (e.g.ul
,ol
).
Detailed Explanation
When Vue processes directives, v-if
has a higher priority than v-for
, so that this template:
<ul>
<li
v-for="user in users"
v-if="user.isActive"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
1
2
3
4
5
6
7
8
9
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:
computed: {
activeUsers() {
return this.users.filter(user => user.isActive)
}
}
1
2
3
4
5
<ul>
<li
v-for="user in activeUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
1
2
3
4
5
6
7
8
Alternatively, we can use a <template>
tag with v-for
to wrap the <li>
element:
<ul>
<template v-for="user in users" :key="user.id">
<li v-if="user.isActive">
{{ user.name }}
</li>
</template>
</ul>
1
2
3
4
5
6
7
Bad
<ul>
<li
v-for="user in users"
v-if="user.isActive"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
1
2
3
4
5
6
7
8
9
Good
<ul>
<li
v-for="user in activeUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
1
2
3
4
5
6
7
8
<ul>
<template v-for="user in users" :key="user.id">
<li v-if="user.isActive">
{{ user.name }}
</li>
</template>
</ul>
1
2
3
4
5
6
7
# Component style scoping essential
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 (opens new window) be used. Scoping could be through CSS modules (opens new window), a class-based strategy such as BEM (opens new window), or another library/convention.
Component libraries, however, should prefer a class-based strategy instead of using the scoped
attribute.
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.
Detailed Explanation
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.
Beyond the 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 button
, btn
, or 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.
Bad
<template>
<button class="btn btn-close">×</button>
</template>
<style>
.btn-close {
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
Good
<template>
<button class="button button-close">×</button>
</template>
<!-- Using the `scoped` attribute -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<button :class="[$style.button, $style.buttonClose]">×</button>
</template>
<!-- Using CSS modules -->
<style module>
.button {
border: none;
border-radius: 2px;
}
.buttonClose {
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<button class="c-Button c-Button--close">×</button>
</template>
<!-- Using the BEM convention -->
<style>
.c-Button {
border: none;
border-radius: 2px;
}
.c-Button--close {
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Private property names essential
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. $_yourPluginName_
).
Detailed Explanation
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.
Bad
const myGreatMixin = {
// ...
methods: {
update() {
// ...
}
}
}
1
2
3
4
5
6
7
8
const myGreatMixin = {
// ...
methods: {
_update() {
// ...
}
}
}
1
2
3
4
5
6
7
8
const myGreatMixin = {
// ...
methods: {
$update() {
// ...
}
}
}
1
2
3
4
5
6
7
8
const myGreatMixin = {
// ...
methods: {
$_update() {
// ...
}
}
}
1
2
3
4
5
6
7
8
Good
const myGreatMixin = {
// ...
methods: {
$_myGreatMixin_update() {
// ...
}
}
}
1
2
3
4
5
6
7
8
// Even better!
const myGreatMixin = {
// ...
methods: {
publicMethod() {
// ...
myPrivateFunction()
}
}
}
function myPrivateFunction() {
// ...
}
export default myGreatMixin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Priority B Rules: Strongly Recommended
# Component files strongly recommended
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.
Bad
app.component('TodoList', {
// ...
})
app.component('TodoItem', {
// ...
})
1
2
3
4
5
6
7
Good
components/
|- TodoList.js
|- TodoItem.js
1
2
3
components/
|- TodoList.vue
|- TodoItem.vue
1
2
3
# Single-file component filename casing strongly recommended
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.
Bad
components/
|- mycomponent.vue
1
2
components/
|- myComponent.vue
1
2
Good
components/
|- MyComponent.vue
1
2
components/
|- my-component.vue
1
2
# Base component names strongly recommended
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 Base
, App
, or V
.
Detailed Explanation
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. BaseButton
, 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 ButtonSubmit
).
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.
MyButton
,VueButton
). -
Since these components are so frequently used, you may want to simply make them global instead of importing them everywhere. A prefix makes this possible with Webpack:
const requireComponent = require.context("./src", true, /Base[A-Z]w+.(vue|js)$/) requireComponent.keys().forEach(function (fileName) { let baseComponentConfig = requireComponent(fileName) baseComponentConfig = baseComponentConfig.default || baseComponentConfig const baseComponentName = baseComponentConfig.name || ( fileName .replace(/^.+//, '') .replace(/.w+$/, '') ) app.component(baseComponentName, baseComponentConfig) })
1
2
3
4
5
6
7
8
9
10
11
Bad
components/
|- MyButton.vue
|- VueTable.vue
|- Icon.vue
1
2
3
4
Good
components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
1
2
3
4
components/
|- AppButton.vue
|- AppTable.vue
|- AppIcon.vue
1
2
3
4
components/
|- VButton.vue
|- VTable.vue
|- VIcon.vue
1
2
3
4
# Single-instance component names strongly recommended
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.
Bad
components/
|- Heading.vue
|- MySidebar.vue
1
2
3
Good
components/
|- TheHeading.vue
|- TheSidebar.vue
1
2
3
# Tightly coupled component names strongly recommended
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.
Detailed Explanation
You might be tempted to solve this problem by nesting child components in directories named after their parent. For example:
components/
|- TodoList/
|- Item/
|- index.vue
|- Button.vue
|- index.vue
1
2
3
4
5
6
or:
components/
|- TodoList/
|- Item/
|- Button.vue
|- Item.vue
|- TodoList.vue
1
2
3
4
5
6
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.
Bad
components/
|- TodoList.vue
|- TodoItem.vue
|- TodoButton.vue
1
2
3
4
components/
|- SearchSidebar.vue
|- NavigationForSearchSidebar.vue
1
2
3
Good
components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
1
2
3
4
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue
1
2
3
# Order of words in component names strongly recommended
Component names should start with the highest-level (often most general) words and end with descriptive modifying words.
Detailed Explanation
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:
components/
|- ClearSearchButton.vue
|- ExcludeFromSearchInput.vue
|- LaunchOnStartupCheckbox.vue
|- RunSearchButton.vue
|- SearchInput.vue
|- TermsCheckbox.vue
1
2
3
4
5
6
7
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:
components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputExcludeGlob.vue
|- SearchInputQuery.vue
|- SettingsCheckboxLaunchOnStartup.vue
|- SettingsCheckboxTerms.vue
1
2
3
4
5
6
7
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
components
directory. - Name conflicts (e.g. multiple
ButtonDelete.vue
components) 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.
Bad
components/
|- ClearSearchButton.vue
|- ExcludeFromSearchInput.vue
|- LaunchOnStartupCheckbox.vue
|- RunSearchButton.vue
|- SearchInput.vue
|- TermsCheckbox.vue
1
2
3
4
5
6
7
Good
components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
|- SettingsCheckboxTerms.vue
|- SettingsCheckboxLaunchOnStartup.vue
1
2
3
4
5
6
7
# Self-closing components strongly recommended
Components with no content should be self-closing in single-file components, string templates, and JSX — but never in DOM templates.
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 (opens new window). 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.
Bad
<!-- In single-file components, string templates, and JSX -->
<MyComponent></MyComponent>
1
2
<!-- In DOM templates -->
<my-component/>
1
2
Good
<!-- In single-file components, string templates, and JSX -->
<MyComponent/>
1
2
<!-- In DOM templates -->
<my-component></my-component>
1
2
# Component name casing in templates strongly recommended
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:
- Editors can autocomplete component names in templates, because PascalCase is also used in JavaScript.
<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.
Bad
<!-- In single-file components and string templates -->
<mycomponent/>
1
2
<!-- In single-file components and string templates -->
<myComponent/>
1
2
<!-- In DOM templates -->
<MyComponent></MyComponent>
1
2
Good
<!-- In single-file components and string templates -->
<MyComponent/>
1
2
<!-- In DOM templates -->
<my-component></my-component>
1
2
OR
<!-- Everywhere -->
<my-component></my-component>
1
2
# Component name casing in JS/JSX strongly recommended
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 app.component
.
Detailed Explanation
In JavaScript, PascalCase is the convention for classes and prototype constructors — essentially, anything that can have distinct instances. Vue components also have instances, so it makes sense to also use PascalCase. As an added benefit, using PascalCase within JSX (and templates) allows readers of the code to more easily distinguish between components and HTML elements.
However, for applications that use only global component definitions via app.component
, we recommend kebab-case instead. The reasons are:
- It’s rare that global components are ever referenced in JavaScript, so following a convention for JavaScript makes less sense.
- These applications always include many in-DOM templates, where kebab-case must be used.
Bad
app.component('myComponent', {
// ...
})
1
2
3
import myComponent from './MyComponent.vue'
1
export default {
name: 'myComponent',
// ...
}
1
2
3
4
export default {
name: 'my-component',
// ...
}
1
2
3
4
Good
app.component('MyComponent', {
// ...
})
1
2
3
app.component('my-component', {
// ...
})
1
2
3
import MyComponent from './MyComponent.vue'
1
export default {
name: 'MyComponent',
// ...
}
1
2
3
4
# Full-word component names strongly recommended
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.
Bad
components/
|- SdSettings.vue
|- UProfOpts.vue
1
2
3
Good
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
1
2
3
# Prop name casing strongly recommended
Prop names should always use camelCase during declaration, but kebab-case in templates and JSX.
We’re simply following the conventions of each language. Within JavaScript, camelCase is more natural. Within HTML, kebab-case is.
Bad
props: {
'greeting-text': String
}
1
2
3
<WelcomeMessage greetingText="hi"/>
1
Good
props: {
greetingText: String
}
1
2
3
<WelcomeMessage greeting-text="hi"/>
1
# Multi-attribute elements strongly recommended
Elements with multiple attributes should span multiple lines, with one attribute per line.
In JavaScript, splitting objects with multiple properties over multiple lines is widely considered a good convention, because it’s much easier to read. Our templates and JSX deserve the same consideration.
Bad
<img src="https://vuejs.org/images/logo.png" alt="Vue Logo">
1
<MyComponent foo="a" bar="b" baz="c"/>
1
Good
<img
src="https://vuejs.org/images/logo.png"
alt="Vue Logo"
>
1
2
3
4
<MyComponent
foo="a"
bar="b"
baz="c"
/>
1
2
3
4
5
# Simple expressions in templates strongly recommended
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.
Bad
{{
fullName.split(' ').map((word) => {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
1
2
3
4
5
Good
<!-- In a template -->
{{ normalizedFullName }}
1
2
// The complex expression has been moved to a computed property
computed: {
normalizedFullName() {
return this.fullName.split(' ')
.map(word => word[0].toUpperCase() + word.slice(1))
.join(' ')
}
}
1
2
3
4
5
6
7
8
# Simple computed properties strongly recommended
Complex computed properties should be split into as many simpler properties as possible.
Detailed Explanation
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 in 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.
Bad
computed: {
price() {
const basePrice = this.manufactureCost / (1 - this.profitMargin)
return (
basePrice -
basePrice * (this.discountPercent || 0)
)
}
}
1
2
3
4
5
6
7
8
9
Good
computed: {
basePrice() {
return this.manufactureCost / (1 - this.profitMargin)
},
discount() {
return this.basePrice * (this.discountPercent || 0)
},
finalPrice() {
return this.basePrice - this.discount
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
# Quoted attribute values strongly recommended
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.
Bad
<AppSidebar :style={width:sidebarWidth+'px'}>
1
Good
<AppSidebar :style="{ width: sidebarWidth + 'px' }">
1
# Directive shorthands strongly recommended
Directive shorthands (:
for v-bind:
, @
for v-on:
and #
for v-slot
) should be used always or never.
Bad
<input
v-bind:value="newTodoText"
:placeholder="newTodoInstructions"
>
1
2
3
4
<input
v-on:input="onInput"
@focus="onFocus"
>
1
2
3
4
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
1
2
3
4
5
6
7
Good
<input
:value="newTodoText"
:placeholder="newTodoInstructions"
>
1
2
3
4
<input
v-bind:value="newTodoText"
v-bind:placeholder="newTodoInstructions"
>
1
2
3
4
<input
@input="onInput"
@focus="onFocus"
>
1
2
3
4
<input
v-on:input="onInput"
v-on:focus="onFocus"
>
1
2
3
4
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
1
2
3
4
5
6
7
<template #header>
<h1>Here might be a page title</h1>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
1
2
3
4
5
6
7
# Priority C Rules: Recommended
# Component/instance options order recommended
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.
-
Global Awareness (requires knowledge beyond the component)
name
-
Template Modifiers (changes the way templates are compiled)
delimiters
-
Template Dependencies (assets used in the template)
components
directives
-
Composition (merges properties into the options)
extends
mixins
provide
/inject
-
Interface (the interface to the component)
inheritAttrs
props
emits
-
Composition API (the entry point for using the Composition API)
setup
-
Local State (local reactive properties)
data
computed
-
Events (callbacks triggered by reactive events)
watch
- Lifecycle Events (in the order they are called)
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
activated
deactivated
beforeUnmount
unmounted
errorCaptured
renderTracked
renderTriggered
-
Non-Reactive Properties (instance properties independent of the reactivity system)
methods
-
Rendering (the declarative description of the component output)
template
/render
# Element attribute order recommended
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)
is
-
List Rendering (creates multiple variations of the same element)
v-for
-
Conditionals (whether the element is rendered/shown)
v-if
v-else-if
v-else
v-show
v-cloak
-
Render Modifiers (changes the way the element renders)
v-pre
v-once
-
Global Awareness (requires knowledge beyond the component)
id
-
Unique Attributes (attributes that require unique values)
ref
key
-
Two-Way Binding (combining binding and events)
v-model
-
Other Attributes (all unspecified bound & unbound attributes)
-
Events (component event listeners)
v-on
-
Content (overrides the content of the element)
v-html
v-text
# Empty lines in component/instance options recommended
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.
Good
props: {
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
},
computed: {
formattedValue() {
// ...
},
inputClasses() {
// ...
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// No spaces are also fine, as long as the component
// is still easy to read and navigate.
props: {
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
},
computed: {
formattedValue() {
// ...
},
inputClasses() {
// ...
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Single-file component top-level element order recommended
Single-file components should always order <script>
, <template>
, and <style>
tags consistently, with <style>
last, because at least one of the other two is always necessary.
Bad
<style>/* ... */</style>
<script>/* ... */</script>
<template>...</template>
1
2
3
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
1
2
3
4
5
6
7
8
9
Good
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
1
2
3
4
5
6
7
8
9
<!-- ComponentA.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
1
2
3
4
5
6
7
8
9
# Priority D Rules: Use with Caution
# Element selectors with scoped
use with caution
Element selectors should be avoided with scoped
.
Prefer class selectors over element selectors in scoped
styles, because large numbers of element selectors are slow.
Detailed Explanation
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. button[data-v-f3f3eg9]
).
The problem is that large numbers of element-attribute selectors (opens new window) (e.g. button[data-v-f3f3eg9]
) will be considerably slower than class-attribute selectors (opens new window) (e.g. .btn-close[data-v-f3f3eg9]
), so class selectors should be preferred whenever possible.
Bad
<template>
<button>×</button>
</template>
<style scoped>
button {
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
Good
<template>
<button class="btn btn-close">×</button>
</template>
<style scoped>
.btn-close {
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
# Implicit parent-child communication use with caution
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).
Bad
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
template: '<input v-model="todo.text">'
})
1
2
3
4
5
6
7
8
9
10
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
methods: {
removeTodo() {
this.$parent.todos = this.$parent.todos.filter(todo => todo.id !== vm.todo.id)
}
},
template: `
<span>
{{ todo.text }}
<button @click="removeTodo">
×
</button>
</span>
`
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Good
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
emits: ['input'],
template: `
<input
:value="todo.text"
@input="$emit('input', $event.target.value)"
>
`
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
emits: ['delete'],
template: `
<span>
{{ todo.text }}
<button @click="$emit('delete')">
×
</button>
</span>
`
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Non-flux state management use with caution
Vuex (opens new window) 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).
Bad
// main.js
import { createApp } from 'vue'
import mitt from 'mitt'
const app = createApp({
data() {
return {
todos: [],
emitter: mitt()
}
},
created() {
this.emitter.on('remove-todo', this.removeTodo)
},
methods: {
removeTodo(todo) {
const todoIdToRemove = todo.id
this.todos = this.todos.filter(todo => todo.id !== todoIdToRemove)
}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Good
// store/modules/todos.js
export default {
state: {
list: []
},
mutations: {
REMOVE_TODO (state, todoId) {
state.list = state.list.filter(todo => todo.id !== todoId)
}
},
actions: {
removeTodo ({ commit, state }, todo) {
commit('REMOVE_TODO', todo.id)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- TodoItem.vue -->
<template>
<span>
{{ todo.text }}
<button @click="removeTodo(todo)">
X
</button>
</span>
</template>
<script>
import { mapActions } from 'vuex'
export default {
props: {
todo: {
type: Object,
required: true
}
},
methods: mapActions(['removeTodo'])
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
pageClass | sidebarDepth | title | description | since |
---|---|---|---|---|
rule-details |
0 |
vue/multi-word-component-names |
require component names to be always multi-word |
v7.20.0 |
vue/multi-word-component-names
require component names to be always multi-word
- ⚙️ This rule is included in all of
"plugin:vue/vue3-essential"
,"plugin:vue/essential"
,"plugin:vue/vue3-strongly-recommended"
,"plugin:vue/strongly-recommended"
,"plugin:vue/vue3-recommended"
and"plugin:vue/recommended"
.
📖 Rule Details
This rule require component names to be always multi-word, except for root App
components, and built-in components provided by Vue, such as <transition>
or
<component>
. This prevents conflicts with existing and future HTML elements,
since all HTML elements are single words.
/* ✓ GOOD */ Vue.component('todo-item', { // ... }) /* ✗ BAD */ Vue.component('Todo', { // ... })
<script> /* ✓ GOOD */ export default { name: 'TodoItem', // ... } </script>
<script> /* ✗ BAD */ export default { name: 'Todo', // ... } </script>
<!-- filename: Todo.vue --> <script> /* ✗ BAD */ export default { // ... } </script>
<!-- filename: Todo.vue --> <!-- ✗ BAD --> <script setup> // ... </script>
<!-- filename: TodoItem.vue --> <!-- ✓ GOOD --> <script setup> // ... </script>
<!-- filename: Todo.vue --> <!-- ✓ GOOD --> <script setup> // ... </script> <script> export default { name: 'TodoItem' } </script>
🔧 Options
{ "vue/multi-word-component-names": ["error", { "ignores": [] }] }
ignores
(string[]
) … The component names to ignore. Sets the component name to allow.
ignores: ["Todo"]
<script> export default { /* ✓ GOOD */ name: 'Todo' } </script>
<script> export default { /* ✗ BAD */ name: 'Item' } </script>
<!-- filename: Todo.vue --> <!-- ✓ GOOD --> <script setup> // ... </script>
📚 Further Reading
- Style guide — Multi-word component names
🚀 Version
This rule was introduced in eslint-plugin-vue v7.20.0
🔍 Implementation
- Rule source
- Test source
Gayathri R
Posted on Apr 22, 2022
• Updated on Jul 3, 2022
Problem:-
While running the VueJs application failed with «Multi-word vue/multi-word-component-names» error.
/home/user/tutorials/animations-vuejs/src/components/HelloWorld.vue
35:9 error Component name "hello" should always be multi-word vue/multi-word-component-names
✖ 1 problem (1 error, 0 warnings)
Enter fullscreen mode
Exit fullscreen mode
Solution:-
This problem is due to the ‘eslint’ setting issues. By default, the linting rule is enabled in Vuejs (Default ([Vue 3] babel, eslint)).
You can resolve this problem in two ways,
Method — 1:
Rename the component name. Here in this case the component name provided is ‘hello’, you can change this as a multi-word like ‘HelloWorld’.
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
Enter fullscreen mode
Exit fullscreen mode
Method — 2:
Disable the linting rule. By disabling the ‘eslint’ execute the below command.
$ npm remove @vue/cli-plugin-eslint
Option 1: Disable globally
To disable the rule in all files (even those in src/components
):
// <projectRoot>/.eslintrc.js
module.exports = {
?
rules: {
'vue/multi-word-component-names': 0,
},
}
Option 2: overrides
in ESLint config for src/views/
To disable the rule only for src/views/**/*.vue
, specify an overrides
config:
// <projectRoot>/.eslintrc.js
module.exports = {
?
overrides: [
{
files: ['src/views/**/*.vue'],
rules: {
'vue/multi-word-component-names': 0,
},
},
],
}
Note: If using VS Code with the ESLint Extension, restarting the ESLint Server (through Command Palette’s >ESLint: Restart ESLint Server
command) or restarting the IDE might be needed to reload the configuration.
Option 3: Directory-level config for src/views/
It’s also possible to disable the rule for src/views/**/*.vue
with an .eslintrc.js
file in that directory:
// <projectRoot>/src/views/.eslintrc.js
module.exports = {
rules: {
'vue/multi-word-component-names': 0,
},
}
For those still having this issue, add the following under rules in the .eslintrc.js
file
rules: {
...
'vue/multi-word-component-names': 0,
}
There’s a simple solution. You need define your component name with more than one word as it states. Should be PascalCase as below;
eg: AboutPage.vue
Find a vue.config.js
file in the project root directory, create one in the root directory if you don’t have one, write the code marked below, save it, and recompile it. The project will run normally
Problems:
In the project created by Vue-cli, after the file is created and named, an error will be reported as “component name” ***** “should always be multi-word”;
The screenshot of error reporting is as follows:
Component name "******" should always be multi-word.eslintvue/multi-word-component-names
Reasons for error reporting:
The naming of components is not standardized. According to the official style guide of eslint, in addition to the root component (app.vue), the user-defined group
The part name should be composed of multiple words (using the naming method of big hump or connecting words with “-“) to prevent conflict with HTML tags;
The project created by the latest vue-cli uses the latest vue/cli-plugin-eslint plugin, which references the vue/multi-word-component-names rule after vue/cli-plugin-eslint v7.20.0.
The vue/multi-word-component-names rule has been referenced since vue/cli-plugin-eslint v7.20.0, so this error was determined at compile time.
Solution:
Scheme 1: Rename (valid for personal test)
Rename the name of the file
Modify the component name to multiple words, use hump naming method or connect words with “-“.
So the problem is solved~~~~
Examples are as follows:
Scheme 2: configure Vue config.js file (online method, invalid for my use)
Find vue.com in the root directory config. JS file (if not, create a new one), and add the following code in Vue config. JS file, add the following code
lintOnSave: false // Close eslint verification
Examples are as follows:
This scheme only does not report errors during compilation. If vscode + eslint is used, a red prompt will be marked in the file header, and the official does not recommend turning off the verification directly;
Configure Vue config. The method of JS file (scheme 2) generally can not solve the problem, so it is not recommended to use it
If you find that you haven’t solved the problem, you might as well try other solutions
Method 3: configuration eslintrc.js file (valid for personal test)
1. Turn off naming rules
Find it eslintrc.js file and adds such a sentence in rules
'vue/multi-word-component-names': "off" // Close name verification
It is suggested to use this method, which is more correct and reasonable;
Examples are as follows:
It is found that there is no error, and it can run normally ~ ~ ~
The above is to close the naming rules, and the component name will not be verified. The official recommended setting is to ignore the component name
2. Ignore individual component names
// Add component naming ignore rule "vue/multi-word-component-names": ["error",{ "ignores": ["Home", "User"]//Component names to ignore }]
Recommended scheme 3, highly recommended!!!
For example:
Scheme 4:
The third scheme is to close and ignore the rule of component name; Ignore by component name
The fourth scheme is the closing rule according to the file.
Close a file naming rule verification
Found in the root directory eslintrc. JS file, (if not, create a new one (note that there is a point in front of the file))
Add the following code to the overrides of the file:
{ files: ['src/views/index.vue','src/views/**/index.vue'], // Match index.vue in views and secondary directories rules: { 'vue/multi-word-component-names': "off", } // assign rules to the files matched above }
Where files: [] is used to match files, and the * sign represents all files. index. Vue can also be changed to * Vue, which is all Vue files in the matching directory
Document content:
module.exports = {
root: true,
env: {
node: true
},
'extends': [
'plugin:vue/essential',
'eslint:recommended'
],
parserOptions: {
parser: '@babel/eslint-parser'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ?'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ?'warn' : 'off',
},
overrides: [
//Here is the code added
{
files: ['src/views/index.vue','src/views/**/index.vue'], // match index.vue in views and secondary directories
rules: {
'vue/multi-word-component-names': "off",
} // Assign rules to the files matched above
},
{
files: [
'**/__tests__/*.{j,t}s?(x)',
'**/tests/unit/**/*.spec.{j,t}s?(x)'
],
env: {
jest: true
}
}
]
}
Four schemes I suggest using scheme 3 and scheme 4. I don’t recommend using the method of scheme 2, which is common on the Internet. It’s not easy to use!
Very important notes: (the configuration file will take effect only after the project is restarted)
In a running project, to modify the configuration file, you must first delete the project in the terminal and click Ctrl + C twice to terminate the project, and then NPM run serve to re run the project. The modified configuration file can take effect
The first solution:
Modify the name of the component as the big hump, do not use the common name in the system
The second solution:
In the root directory, open [.eslintrc.js】File, if not, create new, the code is as follows:
module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin:vue/essential', 'eslint:recommended' ], parserOptions: { parser: '@babel/eslint-parser' }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', //Add custom rules to Rules //Close component naming rules "vue/multi-word-component-names":"off", }, overrides: [ { files: [ '**/__tests__/*.{j,t}s?(x)', '**/tests/unit/**/*.spec.{j,t}s?(x)' ], env: { jest: true } } ] }
After the modification, if it is still not good, you can try to exit VSCODE and enter the project
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
User component names should always be multi-word, except for root App
components. This prevents conflicts with existing and future HTML elements, since all HTML elements are a single word.
Bad
<!-- in pre-compiled templates -->
<Item />
<!-- in in-DOM templates -->
<item></item>
Good
<!-- in pre-compiled templates -->
<TodoItem />
<!-- in in-DOM templates -->
<todo-item></todo-item>
Use detailed prop definitions
In committed code, prop definitions should always be as detailed as possible, specifying at least type(s).
Detailed Explanation
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.
Bad
// This is only OK when prototyping
props: ['status']
Good
props: {
status: String
}
// Even better!
props: {
status: {
type: String,
required: true,
validator: value => {
return [
'syncing',
'synced',
'version-conflict',
'error'
].includes(value)
}
}
}
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 in animations.
Detailed Explanation
Let’s say you have a list of todos:
data() {
return {
todos: [
{
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 <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.
Bad
<ul>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ul>
Good
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
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, replaceusers
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 thev-if
to a container element (e.g.ul
,ol
).
Detailed Explanation
When Vue processes directives, v-if
has a higher priority than v-for
, so that this template:
<ul>
<li
v-for="user in users"
v-if="user.isActive"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
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:
computed: {
activeUsers() {
return this.users.filter(user => user.isActive)
}
}
<ul>
<li
v-for="user in activeUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
Alternatively, we can use a <template>
tag with v-for
to wrap the <li>
element:
<ul>
<template v-for="user in users" :key="user.id">
<li v-if="user.isActive">
{{ user.name }}
</li>
</template>
</ul>
Bad
<ul>
<li
v-for="user in users"
v-if="user.isActive"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
Good
<ul>
<li
v-for="user in activeUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
<ul>
<template v-for="user in users" :key="user.id">
<li v-if="user.isActive">
{{ user.name }}
</li>
</template>
</ul>
Use component-scoped styling
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 scoped
attribute.
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.
Detailed Explanation
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.
Beyond the 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 button
, btn
, or 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.
Bad
<template>
<button class="btn btn-close">×</button>
</template>
<style>
.btn-close {
background-color: red;
}
</style>
Good
<template>
<button class="button button-close">×</button>
</template>
<!-- Using the `scoped` attribute -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
<template>
<button :class="[$style.button, $style.buttonClose]">×</button>
</template>
<!-- Using CSS modules -->
<style module>
.button {
border: none;
border-radius: 2px;
}
.buttonClose {
background-color: red;
}
</style>
<template>
<button class="c-Button c-Button--close">×</button>
</template>
<!-- Using the BEM convention -->
<style>
.c-Button {
border: none;
border-radius: 2px;
}
.c-Button--close {
background-color: red;
}
</style>
Avoid exposing private functions in mixins
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. $_yourPluginName_
).
Detailed Explanation
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.
Bad
const myGreatMixin = {
// ...
methods: {
update() {
// ...
}
}
}
const myGreatMixin = {
// ...
methods: {
_update() {
// ...
}
}
}
const myGreatMixin = {
// ...
methods: {
$update() {
// ...
}
}
}
const myGreatMixin = {
// ...
methods: {
$_update() {
// ...
}
}
}
Good
const myGreatMixin = {
// ...
methods: {
$_myGreatMixin_update() {
// ...
}
}
}
// Even better!
const myGreatMixin = {
// ...
methods: {
publicMethod() {
// ...
myPrivateFunction()
}
}
}
function myPrivateFunction() {
// ...
}
export default myGreatMixin