Logo
首页
前沿
AI热点新闻
36氦头条
博客
开源
极简简历
极简智库
瞬间
相册
友链
知识库
创作者
搜索文章 Ctrl K

Vue 3 官方文档(中文版)

返回 0
  • 导读
  • 开始
    • 简介
    • 快速上手
  • 基础
    • 创建一个应用
    • 模板语法
    • 响应式基础
    • 计算属性
    • 类与样式绑定
    • 条件渲染
    • 列表渲染
    • 事件处理
    • 表单输入绑定
    • 侦听器
    • 模板引用
    • 组件基础
    • 生命周期
  • 深入组件
    • 注册
    • Props
    • 事件
    • 组件-v-model
    • 透传-Attributes
    • 插槽
    • 依赖注入
    • 异步组件
  • 逻辑复用
    • 组合式函数
    • 自定义指令
    • 插件
  • 内置组件
    • Transition
    • TransitionGroup
    • KeepAlive
    • Teleport
    • Suspense
  • 应用规模化
    • 单文件组件
    • 工具链
    • 路由
    • 状态管理
    • 测试
    • 服务端渲染-SSR
  • 最佳实践
    • 生产部署
    • 性能优化
    • 无障碍访问
    • 安全
  • TypeScript
    • 总览
    • TS-与组合式-API
    • TS-与选项式-API
  • 进阶主题
    • 使用-Vue-的多种方式
    • 组合式-API-常见问答
    • 深入响应式系统
    • 渲染机制
    • 渲染函数-&-JSX
    • Vue-与-Web-Components
    • 动画技巧
  • API-参考
    • 全局-API
      • 应用实例
      • 通用
    • 组合式-API
      • setup
      • 响应式--核心
      • 响应式--工具
      • 响应式--进阶
      • 生命周期钩子
      • 依赖注入
      • 辅助
    • 选项式-API
      • 状态选项
      • 渲染选项
      • 生命周期选项
      • 组合选项
      • 其他杂项
      • 组件实例
    • 内置内容
      • 指令
      • 组件
      • 特殊元素
      • 特殊-Attributes
    • 单文件组件
      • 语法定义
      • script-setup
      • CSS-功能
    • 进阶-API
      • 自定义元素
      • 渲染函数
      • 服务端渲染
      • TypeScript-工具类型
      • 自定义渲染
      • 编译时标志
  • 互动教程
    • 第-1-步
    • 开始
    • 声明式渲染
    • Attribute-绑定
    • 事件监听
    • 表单绑定
    • 条件渲染
    • 列表渲染
    • 计算属性
    • 生命周期和模板引用
    • 侦听器
    • 组件
    • Props
    • Emits
    • 插槽
    • 你做到了!
  • 风格指南
    • 概览
    • A---必要的
    • B---强烈推荐
    • C---推荐
    • D---谨慎使用
  • 关于
    • 常见问题
    • 版本发布
    • 社区指南
    • 关于中文翻译

Priority B Rules: 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.

Component files

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.

✗ 反例

app.component('TodoList', {
  // ...
})

app.component('TodoItem', {
  // ...
})

✓ 正例

components/
|- TodoList.js
|- TodoItem.js
components/
|- TodoList.vue
|- TodoItem.vue

Single-file component filename casing

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.

✗ 反例

components/
|- mycomponent.vue
components/
|- myComponent.vue

✓ 正例

components/
|- MyComponent.vue
components/
|- my-component.vue

Base component names

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 Pinia 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 Vite:

    const modules = import.meta.glob('./src/**/Base*.vue', { eager: true })
    for (const path in modules) {
      const config = modules[path].default
      const name = config.name || path.match(/Base[A-Z]\w+/)[0]
      app.component(name, config)
    }
    

✗ 反例

components/
|- MyButton.vue
|- VueTable.vue
|- Icon.vue

✓ 正例

components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
components/
|- AppButton.vue
|- AppTable.vue
|- AppIcon.vue
components/
|- VButton.vue
|- VTable.vue
|- VIcon.vue

Tightly coupled component names

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

or:

components/
|- TodoList/
   |- Item/
      |- Button.vue
   |- Item.vue
|- TodoList.vue

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.

✗ 反例

components/
|- TodoList.vue
|- TodoItem.vue
|- TodoButton.vue
components/
|- SearchSidebar.vue
|- NavigationForSearchSidebar.vue

✓ 正例

components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue

Order of words in component names

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

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

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.

✗ 反例

components/
|- ClearSearchButton.vue
|- ExcludeFromSearchInput.vue
|- LaunchOnStartupCheckbox.vue
|- RunSearchButton.vue
|- SearchInput.vue
|- TermsCheckbox.vue

✓ 正例

components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
|- SettingsCheckboxTerms.vue
|- SettingsCheckboxLaunchOnStartup.vue

Self-closing components

Components with no content should be self-closing in Single-File Components, string templates, and JSX - but never in 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. 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 Single-File Components, string templates, and JSX -->
<MyComponent></MyComponent>
<!-- In in-DOM templates -->
<my-component/>

✓ 正例

<!-- In Single-File Components, string templates, and JSX -->
<MyComponent/>
<!-- In in-DOM templates -->
<my-component></my-component>

Component name casing in templates

In most projects, component names should always be PascalCase in Single-File Components and string templates - but kebab-case in 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, in-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.

✗ 反例

<!-- In Single-File Components and string templates -->
<mycomponent/>
<!-- In Single-File Components and string templates -->
<myComponent/>
<!-- In in-DOM templates -->
<MyComponent></MyComponent>

✓ 正例

<!-- In Single-File Components and string templates -->
<MyComponent/>
<!-- In in-DOM templates -->
<my-component></my-component>

OR

<!-- Everywhere -->
<my-component></my-component>

Component name casing in JS/JSX

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.

[!NOTE] 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.

✗ 反例

app.component('myComponent', {
  // ...
})
import myComponent from './MyComponent.vue'
export default {
  name: 'myComponent'
  // ...
}
export default {
  name: 'my-component'
  // ...
}

✓ 正例

app.component('MyComponent', {
  // ...
})
app.component('my-component', {
  // ...
})
import MyComponent from './MyComponent.vue'
export default {
  name: 'MyComponent'
  // ...
}

Full-word component names

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.

✗ 反例

components/
|- SdSettings.vue
|- UProfOpts.vue

✓ 正例

components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue

Prop name casing

Prop names should always use camelCase during declaration. When used inside in-DOM templates, props should be kebab-cased. Single-File Components templates and JSX can use either kebab-case or camelCase props. Casing should be consistent - if you choose to use camelCased props, make sure you don't use kebab-cased ones in your application

✗ 反例

选项式 API

props: {
  'greeting-text': String
}

组合式 API

const props = defineProps({
  'greeting-text': String
})
// for in-DOM templates
<welcome-message greetingText="hi"></welcome-message>

✓ 正例

选项式 API

props: {
  greetingText: String
}

组合式 API

const props = defineProps({
  greetingText: String
})
// for SFC - please make sure your casing is consistent throughout the project
// you can use either convention but we don't recommend mixing two different casing styles
<WelcomeMessage greeting-text="hi"/>
// or
<WelcomeMessage greetingText="hi"/>
// for in-DOM templates
<welcome-message greeting-text="hi"></welcome-message>

Multi-attribute elements

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.

✗ 反例

<img src="https://vuejs.org/images/logo.png" alt="Vue Logo">
<MyComponent foo="a" bar="b" baz="c"/>

✓ 正例

<img
  src="https://vuejs.org/images/logo.png"
  alt="Vue Logo"
>
<MyComponent
  foo="a"
  bar="b"
  baz="c"
/>

Simple expressions in templates

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.

✗ 反例

{{
  fullName.split(' ').map((word) => {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}

✓ 正例

<!-- In a template -->
{{ normalizedFullName }}

选项式 API

// 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(' ')
  }
}

组合式 API

// The complex expression has been moved to a computed property
const normalizedFullName = computed(() =>
  fullName.value
    .split(' ')
    .map((word) => word[0].toUpperCase() + word.slice(1))
    .join(' ')
)

Simple computed properties

Complex computed properties should be split into as many simpler properties as possible.

[!NOTE] 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.

✗ 反例

选项式 API

computed: {
  price() {
    const basePrice = this.manufactureCost / (1 - this.profitMargin)
    return (
      basePrice -
      basePrice * (this.discountPercent || 0)
    )
  }
}

组合式 API

const price = computed(() => {
  const basePrice = manufactureCost.value / (1 - profitMargin.value)
  return basePrice - basePrice * (discountPercent.value || 0)
})

✓ 正例

选项式 API

computed: {
  basePrice() {
    return this.manufactureCost / (1 - this.profitMargin)
  },

  discount() {
    return this.basePrice * (this.discountPercent || 0)
  },

  finalPrice() {
    return this.basePrice - this.discount
  }
}

组合式 API

const basePrice = computed(
  () => manufactureCost.value / (1 - profitMargin.value)
)

const discount = computed(
  () => basePrice.value * (discountPercent.value || 0)
)

const finalPrice = computed(() => basePrice.value - discount.value)

Quoted attribute values

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.

✗ 反例

<input type=text>
<AppSidebar :style={width:sidebarWidth+'px'}>

✓ 正例

<input type="text">
<AppSidebar :style="{ width: sidebarWidth + 'px' }">

Directive shorthands

Directive shorthands (: for v-bind:, @ for v-on: and # for v-slot) should be used always or never.

✗ 反例

<input
  v-bind:value="newTodoText"
  :placeholder="newTodoInstructions"
>
<input
  v-on:input="onInput"
  @focus="onFocus"
>
<template v-slot:header>
  <h1>Here might be a page title</h1>
</template>

<template #footer>
  <p>Here's some contact info</p>
</template>

✓ 正例

<input
  :value="newTodoText"
  :placeholder="newTodoInstructions"
>
<input
  v-bind:value="newTodoText"
  v-bind:placeholder="newTodoInstructions"
>
<input
  @input="onInput"
  @focus="onFocus"
>
<input
  v-on:input="onInput"
  v-on:focus="onFocus"
>
<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>
<template #header>
  <h1>Here might be a page title</h1>
</template>

<template #footer>
  <p>Here's some contact info</p>
</template>
目录
    共 124 篇 Vue 3 官方文档(中文版) / B---强烈推荐 0 字 0 行 cosolar
    创建 2026-11-08T09:54:58.868075835Z 更新 2026-11-08T09:57:31.446556782Z
    Logo

    以极简为笔,以求索为墨。 简单书写,深度思考,每一次记录,都是与内心的对话。

    30,292 访问量
    219 点赞数
    0 评论数
    162 文章数 13 分类数 243 标签数
    2026-06-06 建站时间
    中国·北京 博主地址

    订阅更新

    订阅我们的技术文章,每周精选内容送达你的邮箱

    隐私政策 | 使用条款 | 友情链接 | 关于我们
    本主题由 腾讯云 提供云服务
    © 极简笔记 版权所有 津ICP备2026156702号-1
    Powered by Halo Theme halo-theme-cosolar