Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 87 ยท TypeScript and Quality

Code Quality and Style

Keep a Vue codebase consistent with the official style guide priorities, ESLint with eslint-plugin-vue, Prettier, clear naming and a sensible file structure.

Working code is the minimum. A codebase that several people will read, change and debug for years also needs to be consistent: the same kinds of things named the same way, formatted the same way, and organized so that you can guess where a file lives. Consistency is not about taste. It reduces the time reviewers spend on arguments, and it lets tools catch whole categories of bugs before the browser does.

This lesson covers the three things that give most of the benefit with the least effort: the official Vue style guide (what to do), ESLint and Prettier (tools that do it for you), and a few conventions for naming and file layout. The runnable examples show two rules in action, so you can see what a linter actually checks.

The official style guide, by priority

The Vue documentation includes a style guide with rules sorted into priority categories. The categories tell you how seriously to take a rule:

Category Purpose Examples
Essential Prevent errors. Do not break these. Multi-word component names, keyed v-for, no v-if on the same element as v-for, detailed prop definitions, component-scoped styles
Strongly recommended Improve readability and developer experience One component per file, PascalCase file names, Base/The name prefixes, self-closing components without content, simple template expressions
Recommended Several equally good options exist; pick one and stay consistent Order of options in a component, order of attributes on an element, blank lines between blocks
Use with caution Features with a downside Element selectors in scoped CSS, implicit parent-child communication

You do not need to memorize the guide. Start with the essential rules, enforce them with a linter, and adopt the rest as a team.

Essential rules in a nutshell

  • Multi-word component names. TodoItem, not Todo. HTML elements are single words, so a multi-word name can never collide with a present or future HTML tag.
  • Keys on v-for. <li v-for="item in items" :key="item.id"> lets Vue match elements to data when the list changes (List Rendering with v-for).
  • Never v-if and v-for on one element. In Vue 3, v-if runs first, so it cannot see the loop variable. Filter with a computed property instead (Conditional Rendering).
  • Detailed props. defineProps({ status: { type: String, required: true } }), or a type in TypeScript, so the contract is documented (Props).
  • Scope your styles. scoped or CSS Modules (Scoped CSS and CSS Modules).

Try it: the v-if with v-for trap and its fix

The first component below puts v-if and v-for on the same <li>. Because v-if is evaluated before the loop variable exists, the render throws. The page installs an error handler (see Debugging Vue) so the failure becomes visible. The second component filters with a computed property and works.

v-if on a v-for element

The bad version renders nothing and reports a TypeError; the good version lists the two open tasks. A linter flags the bad pattern in your editor, long before you open the browser.

ESLint: catching mistakes automatically

ESLint analyzes your code without running it. For Vue, the plugin eslint-plugin-vue adds rules that understand templates, so it can enforce the style guide: vue/multi-word-component-names, vue/require-v-for-key, vue/no-use-v-if-with-v-for, vue/no-mutating-props and many more. The plugin ships rule sets named after the style guide categories (essential, strongly recommended, recommended).

A project created with npm create vue@latest and the ESLint option gets a configuration close to this, written in ESLint's flat config format:

JavaScript
// eslint.config.js
import pluginVue from 'eslint-plugin-vue'
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'

export default defineConfigWithVueTs(
  { files: ['**/*.{ts,vue}'] },
  pluginVue.configs['flat/essential'],
  vueTsConfigs.recommended,
)

Run it with npx eslint ., or npx eslint . --fix to apply automatic fixes. Choose the flat/strongly-recommended or flat/recommended sets once the essential ones pass cleanly.

Turn rules on gradually in an existing codebase. Start with the essential set, fix what it finds, commit, then add the next set. Enabling everything at once buries the real bugs under thousands of style warnings.

Try it: a tiny template linter

A linter is not magic. It parses code and checks a rule. This toy version looks for the two template rules above using a regular expression. (The real plugin builds a proper syntax tree, so it is far more accurate. This sketch is only here to demystify the idea.) Edit the template and watch the report update.

What a lint rule does

Line 1 lacks a key and line 2 combines v-if with v-for; line 3 is fine. Add :key="item" to the first line and one problem disappears. That feedback loop, at the speed of typing, is why teams run the linter inside the editor.

Prettier: formatting without debates

Prettier is a formatter. It rewrites your code into one canonical layout (line breaks, quotes, indentation, semicolons) so nobody argues about them in review. It understands .vue files, including the template, script and style blocks.

JSON
{
  "semi": false,
  "singleQuote": true,
  "printWidth": 100
}

Keep the two tools in separate lanes: Prettier formats, ESLint finds problems. A style rule in ESLint that conflicts with Prettier causes endless fix-and-revert loops, so use a config that turns off formatting rules in ESLint (create-vue sets this up for you). Typical scripts:

JSON
{
  "scripts": {
    "lint": "eslint . --fix",
    "format": "prettier --write src/"
  }
}
flowchart LR
  A["Save in editor<br/>format + lint hints"] --> B["Pre-commit hook<br/>lint-staged on changed files"]
  B --> C["Pull request<br/>CI runs lint + type-check + tests"]
  C --> D["Merge"]

The same checks run at three points, each one stricter and slower than the last.

Run the checks in the editor for instant feedback, in a pre-commit hook for changed files, and in CI as the final gate (alongside vue-tsc from TypeScript with Vue). CI is the one that cannot be skipped.

Naming conventions

Good names make a component tree readable like an outline.

  • Components: PascalCase file names and tags, always more than one word: UserCard.vue, used as <UserCard />.
  • Base components (generic buttons, inputs) share a prefix: BaseButton, BaseInput. Single-instance components use The: TheHeader, TheSidebar.
  • Tightly coupled components extend the parent's name: TodoList.vue, TodoListItem.vue, TodoListItemButton.vue. They sort next to each other in the file tree.
  • Props: camelCase in JavaScript (isActive), kebab-case in templates (is-active), though PascalCase components accept either.
  • Events: emit camelCase names (emit('itemSelected')) and listen with kebab-case in templates (@item-selected), or use one style consistently.
  • Composables: start with use (useMouse, useFetch; see Composables).
  • Booleans read like questions: isOpen, hasError, canSubmit.
  • Full words over abbreviations: selectedUser, not selUsr.

File structure

For small apps, folders by type work (components/, composables/, views/, stores/). When the app grows, folders by feature keep related code together:

TEXT
src/
  components/        shared, generic components (BaseButton.vue, BaseModal.vue)
  composables/       shared logic (useDebounce.ts)
  features/
    todos/
      TodoList.vue
      TodoListItem.vue
      useTodos.ts
      todos-api.ts
    account/
      AccountForm.vue
      useAccount.ts
  views/             one file per route (HomeView.vue)
  App.vue
  main.ts

Start simple and split when navigating hurts, not before. The Designing Components lesson covers how to decide where one component should end and the next begin.

Component conventions that pay off

  • One consistent block order in every SFC. Many teams use <script setup>, then <template>, then <style>; others put the template first. The point is to choose one.
  • Inside <script setup>: imports, props and emits, state, computed values, watchers, functions, lifecycle hooks. Group related logic together, or move it into a composable.
  • Keep templates simple. Expressions like items.filter(...).map(...) belong in a computed, with a name that says what it means.
  • Props down, events up. Never mutate a prop; emit an event or use defineModel.
  • Short components. If a component needs scrolling to understand, extract a child or a composable.
  • Comment the why, not the what. The code already says what it does.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the style guide require multi-word component names?

    A component named Todo might clash with a future HTML element. TodoItem cannot, because standard HTML tags are single words.
  2. 2. What goes wrong with <li v-for="t in tasks" v-if="!t.done">?

    v-if has higher priority than v-for in Vue 3. Filter with a computed property, or wrap the loop in a template and put v-if on the inner element.
  3. 3. How should ESLint and Prettier divide the work?

    Overlapping formatting rules fight each other. Letting Prettier own layout and ESLint own correctness keeps both tools quick and predictable.
  4. 4. Where must lint and type checks run so that they cannot be skipped?

    Editor and pre-commit checks give quick feedback but can be bypassed. A CI job on every pull request is the gate everyone shares.

Summary

  • The Vue style guide sorts rules into essential, strongly recommended, recommended and use-with-caution; start with the essential ones.
  • eslint-plugin-vue enforces template-aware rules such as keyed v-for and no v-if with v-for; adopt rule sets gradually.
  • Prettier owns formatting and ESLint owns correctness, so keep their rules from overlapping.
  • Run checks in the editor, in a pre-commit hook and in CI.
  • Use PascalCase multi-word component names with consistent prefixes (Base, The) and name coupled components by extending the parent's name.
  • Organize by feature when the app grows, keep templates simple and move logic into computed properties and composables.

Next: Accessibility in Vue