` 元素。它包含我们创建实际元素所需的所有信息。它还包含更多的子节点,这使它成为虚拟 DOM 树的根节点。
一个运行时渲染器将会遍历整个虚拟 DOM 树,并据此构建真实的 DOM 树。这个过程被称为**挂载** (mount)。
如果我们有两份虚拟 DOM 树,渲染器也可以遍历并比较这两棵树,找出它们之间的差异,并将这些变化应用到真实的 DOM 上。这个过程被称为**更新** (patch),又被称为“比对”(diffing) 或“协调”(reconciliation)。
虚拟 DOM 带来的主要收益是它让开发者能够灵活、声明式地创建、检查和组合所需 UI 的结构,同时只需把具体的 DOM 操作留给渲染器去处理。
## 渲染管线 {#render-pipeline}
从高层面的视角看,Vue 组件挂载时会发生如下几件事:
1. **编译**:Vue 模板被编译为**渲染函数**:即用来返回虚拟 DOM 树的函数。这一步骤可以通过构建步骤提前完成,也可以通过使用运行时编译器即时完成。
2. **挂载**:运行时渲染器调用渲染函数,遍历返回的虚拟 DOM 树,并基于它创建实际的 DOM 节点。这一步会作为[响应式副作用](./reactivity-in-depth)执行,因此它会追踪其中所用到的所有响应式依赖。
3. **更新**:当挂载期间用到的某个依赖发生变化时,副作用会重新运行,这时候会创建一个更新后的虚拟 DOM 树。运行时渲染器遍历这棵新树,将它与旧树进行比较,然后将必要的更新应用到真实 DOM 上去。

## 模板 vs. 渲染函数 {#templates-vs-render-functions}
Vue 模板会被预编译成虚拟 DOM 渲染函数。Vue 也提供了 API 使我们可以不使用模板编译,直接手写渲染函数。在处理高度动态的逻辑时,渲染函数相比于模板更加灵活,因为你可以完全地使用 JavaScript 来构造你想要的 vnode。
那么为什么 Vue 默认推荐使用模板呢?有以下几点原因:
1. 模板更贴近实际的 HTML。这使得我们能够更方便地重用一些已有的 HTML 代码片段,能够带来更好的可访问性体验、能更方便地使用 CSS 应用样式,并且更容易使设计师理解和修改。
2. 由于其确定的语法,更容易对模板做静态分析。这使得 Vue 的模板编译器能够应用许多编译时优化来提升虚拟 DOM 的性能表现 (下面我们将展开讨论)。
在实践中,模板对大多数的应用场景都是够用且高效的。渲染函数一般只会在需要处理高度动态渲染逻辑的可重用组件中使用。想了解渲染函数的更多使用细节可以去到[渲染函数 & JSX](./render-function) 章节继续阅读。
## 带编译时信息的虚拟 DOM {#compiler-informed-virtual-dom}
虚拟 DOM 在 React 和大多数其他实现中都是纯运行时的:更新算法无法预知新的虚拟 DOM 树会是怎样,因此它总是需要遍历整棵树、比较每个 vnode 上 props 的区别来确保正确性。另外,即使一棵树的某个部分从未改变,还是会在每次重渲染时创建新的 vnode,带来了大量不必要的内存压力。这也是虚拟 DOM 最受诟病的地方之一:这种有点暴力的更新过程通过牺牲效率来换取声明式的写法和最终的正确性。
但实际上我们并不需要这样。在 Vue 中,框架同时控制着编译器和运行时。这使得我们可以为紧密耦合的模板渲染器应用许多编译时优化。编译器可以静态分析模板并在生成的代码中留下标记,使得运行时尽可能地走捷径。与此同时,我们仍旧保留了边界情况时用户想要使用底层渲染函数的能力。我们称这种混合解决方案为**带编译时信息的虚拟 DOM**。
下面,我们将讨论一些 Vue 编译器用来提高虚拟 DOM 运行时性能的主要优化:
### 缓存静态内容 {#cache-static}
在模板中常常有部分内容是不带任何动态绑定的:
```vue-html{2-3}
```
[在模板编译预览中查看](https://template-explorer.vuejs.org/#eyJzcmMiOiI8ZGl2PlxuICA8ZGl2PmZvbzwvZGl2PiA8IS0tIGNhY2hlZCAtLT5cbiAgPGRpdj5iYXI8L2Rpdj4gPCEtLSBjYWNoZWQgLS0+XG4gIDxkaXY+e3sgZHluYW1pYyB9fTwvZGl2PlxuPC9kaXY+XG4iLCJvcHRpb25zIjp7ImhvaXN0U3RhdGljIjp0cnVlfX0=)
`foo` 和 `bar` 这两个 div 是完全静态的,没有必要在重新渲染时再次创建和比对它们。渲染器在首次渲染时会将创建的这部分 vnode 缓存起来,并在后续的重新渲染中使用缓存的 vnode,渲染器知道新旧 vnode 在这部分是完全相同的,所以会完全跳过对它们的差异比对。
此外,当有足够多连续的静态元素时,它们还会再被压缩为一个“静态 vnode”,其中包含的是这些节点相应的纯 HTML 字符串。([示例](https://template-explorer.vuejs.org/#eyJzcmMiOiI8ZGl2PlxuICA8ZGl2IGNsYXNzPVwiZm9vXCI+Zm9vPC9kaXY+XG4gIDxkaXYgY2xhc3M9XCJmb29cIj5mb288L2Rpdj5cbiAgPGRpdiBjbGFzcz1cImZvb1wiPmZvbzwvZGl2PlxuICA8ZGl2IGNsYXNzPVwiZm9vXCI+Zm9vPC9kaXY+XG4gIDxkaXYgY2xhc3M9XCJmb29cIj5mb288L2Rpdj5cbiAgPGRpdj57eyBkeW5hbWljIH19PC9kaXY+XG48L2Rpdj4iLCJzc3IiOmZhbHNlLCJvcHRpb25zIjp7ImhvaXN0U3RhdGljIjp0cnVlfX0=))。这些静态节点会直接通过 `innerHTML` 来挂载。
### 更新类型标记 {#patch-flags}
对于单个有动态绑定的元素来说,我们可以在编译时推断出大量信息:
```vue-html
{{ dynamic }}
```
[在模板编译预览中查看](https://template-explorer.vuejs.org/#eyJzcmMiOiI8ZGl2IDpjbGFzcz1cInsgYWN0aXZlIH1cIj48L2Rpdj5cblxuPGlucHV0IDppZD1cImlkXCIgOnZhbHVlPVwidmFsdWVcIj5cblxuPGRpdj57eyBkeW5hbWljIH19PC9kaXY+Iiwib3B0aW9ucyI6e319)
在为这些元素生成渲染函数时,Vue 在 vnode 创建调用中直接编码了每个元素所需的更新类型:
```js{3}
createElementVNode("div", {
class: _normalizeClass({ active: _ctx.active })
}, null, 2 /* CLASS */)
```
最后这个参数 `2` 就是一个[更新类型标记 (patch flag)](https://github.com/vuejs/core/blob/main/packages/shared/src/patchFlags.ts)。一个元素可以有多个更新类型标记,会被合并成一个数字。运行时渲染器也将会使用[位运算](https://en.wikipedia.org/wiki/Bitwise_operation)来检查这些标记,确定相应的更新操作:
```js
if (vnode.patchFlag & PatchFlags.CLASS /* 2 */) {
// 更新节点的 CSS class
}
```
位运算检查是非常快的。通过这样的更新类型标记,Vue 能够在更新带有动态绑定的元素时做最少的操作。
Vue 也为 vnode 的子节点标记了类型。举例来说,包含多个根节点的模板被表示为一个片段 (fragment),大多数情况下,我们可以确定其顺序是永远不变的,所以这部分信息就可以提供给运行时作为一个更新类型标记。
```js{4}
export function render() {
return (_openBlock(), _createElementBlock(_Fragment, null, [
/* children */
], 64 /* STABLE_FRAGMENT */))
}
```
运行时会完全跳过对这个根片段中子元素顺序的重新协调过程。
### 树结构打平 {#tree-flattening}
再来看看上面这个例子中生成的代码,你会发现所返回的虚拟 DOM 树是经一个特殊的 `createElementBlock()` 调用创建的:
```js{2}
export function render() {
return (_openBlock(), _createElementBlock(_Fragment, null, [
/* children */
], 64 /* STABLE_FRAGMENT */))
}
```
从概念上讲,“区块”是模板中内部结构保持稳定的一个部分。在这个用例中,整个模板只有一个区块,因为这里没有用到任何结构性指令 (比如 `v-if` 或者 `v-for`)。
每一个块都会追踪其所有带更新类型标记的后代节点 (不只是直接子节点),举例来说:
```vue-html{3,5}
```
编译的结果会被打平为一个数组,仅包含所有动态的后代节点:
```
div (block root)
- div 带有 :id 绑定
- div 带有 {{ bar }} 绑定
```
当这个组件需要重渲染时,只需要遍历这个打平的树而非整棵树。这也就是我们所说的**树结构打平**,这大大减少了我们在虚拟 DOM 协调时需要遍历的节点数量。模板中任何的静态部分都会被高效地略过。
`v-if` 和 `v-for` 指令会创建新的区块节点:
```vue-html
```
一个子区块会在父区块的动态子节点数组中被追踪,这为他们的父区块保留了一个稳定的结构。
### 对 SSR 激活的影响 {#impact-on-ssr-hydration}
更新类型标记和树结构打平都大大提升了 Vue [SSR 激活](/guide/scaling-up/ssr#client-hydration)的性能表现:
* 单个元素的激活可以基于相应 vnode 的更新类型标记走更快的捷径。
* 在激活时只有区块节点和其动态子节点需要被遍历,这在模板层面上实现更高效的部分激活。
---
---
url: /guide/extras/render-function.md
---
# 渲染函数 & JSX {#render-functions-jsx}
在绝大多数情况下,Vue 推荐使用模板语法来创建应用。然而在某些使用场景下,我们真的需要用到 JavaScript 完全的编程能力。这时**渲染函数**就派上用场了。
> 如果你还不熟悉虚拟 DOM 和渲染函数的概念的话,请确保先阅读[渲染机制](/guide/extras/rendering-mechanism)章节。
## 基本用法 {#basic-usage}
### 创建 Vnodes {#creating-vnodes}
Vue 提供了一个 `h()` 函数用于创建 vnodes:
```js
import { h } from 'vue'
const vnode = h(
'div', // type
{ id: 'foo', class: 'bar' }, // props
[
/* children */
]
)
```
`h()` 是 **hyperscript** 的简称——意思是“能生成 HTML (超文本标记语言) 的 JavaScript”。这个名字来源于许多虚拟 DOM 实现默认形成的约定。一个更准确的名称应该是 `createVNode()`,但当你需要多次使用渲染函数时,一个简短的名字会更省力。
`h()` 函数的使用方式非常的灵活:
```js
// 除了类型必填以外,其他的参数都是可选的
h('div')
h('div', { id: 'foo' })
// attribute 和 property 都能在 prop 中书写
// Vue 会自动将它们分配到正确的位置
h('div', { class: 'bar', innerHTML: 'hello' })
// 像 `.prop` 和 `.attr` 这样的属性修饰符
// 可以分别通过 `.` 和 `^` 前缀来添加
h('div', { '.name': 'some-name', '^width': '100' })
// 类与样式可以像在模板中一样
// 用数组或对象的形式书写
h('div', { class: [foo, { bar }], style: { color: 'red' } })
// 事件监听器应以 onXxx 的形式书写
h('div', { onClick: () => {} })
// children 可以是一个字符串
h('div', { id: 'foo' }, 'hello')
// 没有 props 时可以省略不写
h('div', 'hello')
h('div', [h('span', 'hello')])
// children 数组可以同时包含 vnodes 与字符串
h('div', ['hello', h('span', 'hello')])
```
得到的 vnode 为如下形式:
```js
const vnode = h('div', { id: 'foo' }, [])
vnode.type // 'div'
vnode.props // { id: 'foo' }
vnode.children // []
vnode.key // null
```
::: warning 注意事项
完整的 `VNode` 接口包含其他内部属性,但是强烈建议避免使用这些没有在这里列举出的属性。这样能够避免因内部属性变更而导致的不兼容性问题。
:::
### 声明渲染函数 {#declaring-render-function}
当组合式 API 与模板一起使用时,`setup()` 钩子的返回值是用于暴露数据给模板。然而当我们使用渲染函数时,可以直接把渲染函数返回:
```js
import { ref, h } from 'vue'
export default {
props: {
/* ... */
},
setup(props) {
const count = ref(1)
// 返回渲染函数
return () => h('div', props.msg + count.value)
}
}
```
在 `setup()` 内部声明的渲染函数天生能够访问在同一范围内声明的 props 和许多响应式状态。
除了返回一个 vnode,你还可以返回字符串或数组:
```js
export default {
setup() {
return () => 'hello world!'
}
}
```
```js
import { h } from 'vue'
export default {
setup() {
// 使用数组返回多个根节点
return () => [
h('div'),
h('div'),
h('div')
]
}
}
```
::: tip
请确保返回的是一个函数而不是一个值!`setup()` 函数在每个组件中只会被调用一次,而返回的渲染函数将会被调用多次。
:::
我们可以使用 `render` 选项来声明渲染函数:
```js
import { h } from 'vue'
export default {
data() {
return {
msg: 'hello'
}
},
render() {
return h('div', this.msg)
}
}
```
`render()` 函数可以访问同一个 `this` 组件实例。
除了返回一个单独的 vnode 之外,你还可以返回字符串或是数组:
```js
export default {
render() {
return 'hello world!'
}
}
```
```js
import { h } from 'vue'
export default {
render() {
// 用数组来返回多个根节点
return [
h('div'),
h('div'),
h('div')
]
}
}
```
如果一个渲染函数组件不需要任何实例状态,为了简洁起见,它们也可以直接被声明为一个函数:
```js
function Hello() {
return 'hello world!'
}
```
没错,这就是一个合法的 Vue 组件!参阅[函数式组件](#functional-components)来了解更多语法细节。
### Vnodes 必须唯一 {#vnodes-must-be-unique}
组件树中的 vnodes 必须是唯一的。下面是错误示范:
```js
function render() {
const p = h('p', 'hi')
return h('div', [
// 啊哦,重复的 vnodes 是无效的
p,
p
])
}
```
如果你真的非常想在页面上渲染多个重复的元素或者组件,你可以使用一个工厂函数来做这件事。比如下面的这个渲染函数就可以完美渲染出 20 个相同的段落:
```js
function render() {
return h(
'div',
Array.from({ length: 20 }).map(() => {
return h('p', 'hi')
})
)
}
```
### 在 `
` 中使用 Vnode {#using-vnodes-in-template}
```vue
Hi
Hi
```
由于 vnode 对象已经在 `setup()` 中定义,你可以像普通组件那样直接渲染它。
:::warning
一个 vnode 表示的是一个静态的渲染输出,而不是一个组件定义。在 `` 中使用 vnode 并不会创建一个新的组件实例,vnode 将按它原样渲染。
这种用法需要特别注意,它不是组件的替代品。
:::
## JSX / TSX {#jsx-tsx}
[JSX](https://react.dev/learn/writing-markup-with-jsx) 是 JavaScript 的一个类似 XML 的扩展,有了它,我们可以用以下的方式来书写代码:
```jsx
const vnode = hello
```
在 JSX 表达式中,使用大括号来嵌入动态值:
```jsx
const vnode = hello, {userName}
```
`create-vue` 和 Vue CLI 都有预置的 JSX 语法支持。如果你想手动配置 JSX,请参阅 [`@vue/babel-plugin-jsx`](https://github.com/vuejs/jsx-next) 文档获取更多细节。
虽然最早是由 React 引入,但实际上 JSX 语法并没有定义运行时语义,并且能被编译成各种不同的输出形式。如果你之前使用过 JSX 语法,那么请注意 **Vue 的 JSX 转换方式与 React 中 JSX 的转换方式不同**,因此你不能在 Vue 应用中使用 React 的 JSX 转换。与 React JSX 语法的一些明显区别包括:
* 可以使用 HTML attributes 比如 `class` 和 `for` 作为 props - 不需要使用 `className` 或 `htmlFor`。
* 传递子元素给组件 (比如 slots) 的[方式不同](#passing-slots)。
Vue 的类型定义也提供了 TSX 语法的类型推导支持。当使用 TSX 语法时,确保在 `tsconfig.json` 中配置了 `"jsx": "preserve"`,这样的 TypeScript 就能保证 Vue JSX 语法转换过程中的完整性。
### JSX 类型推断 {#jsx-type-inference}
与转换类似,Vue 的 JSX 也需要不同的类型定义。
从 Vue 3.4 开始,Vue 不再隐式注册全局 `JSX` 命名空间。要指示 TypeScript 使用 Vue 的 JSX 类型定义,请确保在你的 `tsconfig.json` 中包含以下内容:
```json
{
"compilerOptions": {
"jsx": "preserve",
"jsxImportSource": "vue"
// ...
}
}
```
你也可以通过在文件的顶部加入 `/* @jsxImportSource vue */` 注释来选择性地开启。
如果仍有代码依赖于全局存在的 `JSX` 命名空间,你可以在项目中通过显式导入或引用 `vue/jsx` 来保留 3.4 之前的全局行为,它注册了全局 `JSX` 命名空间。
## 渲染函数案例 {#render-function-recipes}
下面我们提供了几个常见的用等价的渲染函数 / JSX 语法,实现模板功能的案例:
### `v-if` {#v-if}
模板:
```vue-html
```
等价于使用如下渲染函数 / JSX 语法:
```js
h('div', [ok.value ? h('div', 'yes') : h('span', 'no')])
```
```jsx
```
```js
h('div', [this.ok ? h('div', 'yes') : h('span', 'no')])
```
```jsx
```
### `v-for` {#v-for}
模板:
```vue-html
```
等价于使用如下渲染函数 / JSX 语法:
```js
h(
'ul',
// assuming `items` is a ref with array value
items.value.map(({ id, text }) => {
return h('li', { key: id }, text)
})
)
```
```jsx
{items.value.map(({ id, text }) => {
return - {text}
})}
```
```js
h(
'ul',
this.items.map(({ id, text }) => {
return h('li', { key: id }, text)
})
)
```
```jsx
{this.items.map(({ id, text }) => {
return - {text}
})}
```
### `v-on` {#v-on}
以 `on` 开头,并跟着大写字母的 props 会被当作事件监听器。比如,`onClick` 与模板中的 `@click` 等价。
```js
h(
'button',
{
onClick(event) {
/* ... */
}
},
'Click Me'
)
```
```jsx
```
#### 事件修饰符 {#event-modifiers}
对于 `.passive`、`.capture` 和 `.once` 事件修饰符,可以使用驼峰写法将他们拼接在事件名后面:
实例:
```js
h('input', {
onClickCapture() {
/* 捕捉模式中的监听器 */
},
onKeyupOnce() {
/* 只触发一次 */
},
onMouseoverOnceCapture() {
/* 单次 + 捕捉 */
}
})
```
```jsx
{}}
onKeyupOnce={() => {}}
onMouseoverOnceCapture={() => {}}
/>
```
对于事件和按键修饰符,可以使用 [`withModifiers`](/api/render-function#withmodifiers) 函数:
```js
import { withModifiers } from 'vue'
h('div', {
onClick: withModifiers(() => {}, ['self'])
})
```
```jsx
{}, ['self'])} />
```
### 组件 {#components}
在给组件创建 vnode 时,传递给 `h()` 函数的第一个参数应当是组件的定义。这意味着使用渲染函数时不再需要注册组件了 —— 可以直接使用导入的组件:
```js
import Foo from './Foo.vue'
import Bar from './Bar.jsx'
function render() {
return h('div', [h(Foo), h(Bar)])
}
```
```jsx
function render() {
return (
)
}
```
不管是什么类型的文件,只要从中导入的是有效的 Vue 组件,`h` 就能正常运作。
动态组件在渲染函数中也可直接使用:
```js
import Foo from './Foo.vue'
import Bar from './Bar.jsx'
function render() {
return ok.value ? h(Foo) : h(Bar)
}
```
```jsx
function render() {
return ok.value ?
:
}
```
如果一个组件是用名字注册的,不能直接导入 (例如,由一个库全局注册),可以使用 [`resolveComponent()`](/api/render-function#resolvecomponent) 来解决这个问题。
### 渲染插槽 {#rendering-slots}
在渲染函数中,插槽可以通过 `setup()` 的上下文来访问。每个 `slots` 对象中的插槽都是一个**返回 vnodes 数组的函数**:
```js
export default {
props: ['message'],
setup(props, { slots }) {
return () => [
// 默认插槽:
//
h('div', slots.default()),
// 具名插槽:
//
h(
'div',
slots.footer({
text: props.message
})
)
]
}
}
```
等价 JSX 语法:
```jsx
// 默认插槽
{slots.default()}
// 具名插槽
{slots.footer({ text: props.message })}
```
在渲染函数中,可以通过 [this.$slots](/api/component-instance#slots) 来访问插槽:
```js
export default {
props: ['message'],
render() {
return [
//
h('div', this.$slots.default()),
//
h(
'div',
this.$slots.footer({
text: this.message
})
)
]
}
}
```
等价 JSX 语法:
```jsx
//
{this.$slots.default()}
//
{this.$slots.footer({ text: this.message })}
```
### 传递插槽 {#passing-slots}
向组件传递子元素的方式与向元素传递子元素的方式有些许不同。我们需要传递一个插槽函数或者是一个包含插槽函数的对象而非是数组,插槽函数的返回值同一个正常的渲染函数的返回值一样——并且在子组件中被访问时总是会被转化为一个 vnodes 数组。
```js
// 单个默认插槽
h(MyComponent, () => 'hello')
// 具名插槽
// 注意 `null` 是必需的
// 以避免 slot 对象被当成 prop 处理
h(MyComponent, null, {
default: () => 'default slot',
foo: () => h('div', 'foo'),
bar: () => [h('span', 'one'), h('span', 'two')]
})
```
等价 JSX 语法:
```jsx
// 默认插槽
{() => 'hello'}
// 具名插槽
{{
default: () => 'default slot',
foo: () => foo
,
bar: () => [one, two]
}}
```
插槽以函数的形式传递使得它们可以被子组件懒调用。这能确保它被注册为子组件的依赖关系,而不是父组件。这使得更新更加准确及有效。
### 作用域插槽 {#scoped-slots}
为了在父组件中渲染作用域插槽,需要给子组件传递一个插槽。注意该插槽现在拥有一个 `text` 参数。该插槽将在子组件中被调用,同时子组件中的数据将向上传递给父组件。
```js
// 父组件
export default {
setup() {
return () => h(MyComp, null, {
default: ({ text }) => h('p', text)
})
}
}
```
记得传递 `null` 以避免插槽被误认为 prop:
```js
// 子组件
export default {
setup(props, { slots }) {
const text = ref('hi')
return () => h('div', null, slots.default({ text: text.value }))
}
}
```
等同于 JSX:
```jsx
{{
default: ({ text }) => { text }
}}
```
### 内置组件 {#built-in-components}
诸如 `
`、``、``、`` 和 `` 等[内置组件](/api/built-in-components)在渲染函数中必须导入才能使用:
```js
import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue'
export default {
setup () {
return () => h(Transition, { mode: 'out-in' }, /* ... */)
}
}
```
```js
import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue'
export default {
render () {
return h(Transition, { mode: 'out-in' }, /* ... */)
}
}
```
### `v-model` {#v-model}
`v-model` 指令扩展为 `modelValue` 和 `onUpdate:modelValue` 在模板编译过程中,我们必须自己提供这些 props:
```js
export default {
props: ['modelValue'],
emits: ['update:modelValue'],
setup(props, { emit }) {
return () =>
h(SomeComponent, {
modelValue: props.modelValue,
'onUpdate:modelValue': (value) => emit('update:modelValue', value)
})
}
}
```
```js
export default {
props: ['modelValue'],
emits: ['update:modelValue'],
render() {
return h(SomeComponent, {
modelValue: this.modelValue,
'onUpdate:modelValue': (value) => this.$emit('update:modelValue', value)
})
}
}
```
### 自定义指令 {#custom-directives}
可以使用 [`withDirectives`](/api/render-function#withdirectives) 将自定义指令应用于 vnode:
```js
import { h, withDirectives } from 'vue'
// 自定义指令
const pin = {
mounted() { /* ... */ },
updated() { /* ... */ }
}
//
const vnode = withDirectives(h('div'), [
[pin, 200, 'top', { animate: true }]
])
```
当一个指令是以名称注册并且不能被直接导入时,可以使用 [`resolveDirective`](/api/render-function#resolvedirective) 函数来解决这个问题。
### 模板引用 {#template-refs}
在组合式 API 中使用 [`useTemplateRef()`](/api/composition-api-helpers#usetemplateref) 时,模板引用是通过将字符串值作为 prop 传递给 vnode 创建的:
```js
import { h, useTemplateRef } from 'vue'
export default {
setup() {
const divEl = useTemplateRef('my-div')
//
return () => h('div', { ref: 'my-div' })
}
}
```
在 3.5 版本之前 useTemplateRef() 暂未引入,模板引用是通过将 ref() 本身作为 prop 传递给 vnode 创建的:
```js
import { h, ref } from 'vue'
export default {
setup() {
const divEl = ref()
//
return () => h('div', { ref: divEl })
}
}
```
在选项式 API 中,模板引用通过在 vnode 参数中传递字符串类型的引用名称来创建:
```js
export default {
render() {
//
return h('div', { ref: 'divEl' })
}
}
```
## 函数式组件 {#functional-components}
函数式组件是一种定义自身没有任何状态的组件的方式。它们很像纯函数:接收 props,返回 vnodes。函数式组件在渲染过程中不会创建组件实例 (也就是说,没有 `this`),也不会触发常规的组件生命周期钩子。
我们用一个普通的函数而不是一个选项对象来创建函数式组件。该函数实际上就是该组件的渲染函数。
函数式组件的签名与 `setup()` 钩子相同:
```js
function MyComponent(props, { slots, emit, attrs }) {
// ...
}
```
而因为函数式组件里没有 `this` 引用,Vue 会把 `props` 当作第一个参数传入:
```js
function MyComponent(props, context) {
// ...
}
```
第二个参数 `context` 包含三个属性:`attrs`、`emit` 和 `slots`。它们分别相当于组件实例的 [`$attrs`](/api/component-instance#attrs)、[`$emit`](/api/component-instance#emit) 和 [`$slots`](/api/component-instance#slots) 这几个属性。
大多数常规组件的配置选项在函数式组件中都不可用,除了 [`props`](/api/options-state#props) 和 [`emits`](/api/options-state#emits)。我们可以给函数式组件添加对应的属性来声明它们:
```js
MyComponent.props = ['value']
MyComponent.emits = ['click']
```
如果这个 `props` 选项没有被定义,那么被传入函数的 `props` 对象就会像 `attrs` 一样会包含所有 attribute。除非指定了 `props` 选项,否则每个 prop 的名字将不会基于驼峰命名法被一般化处理。
对于有明确 `props` 的函数式组件,[attribute 透传](/guide/components/attrs)的原理与普通组件基本相同。然而,对于没有明确指定 `props` 的函数式组件,只有 `class`、`style` 和 `onXxx` 事件监听器将默认从 `attrs` 中继承。在这两种情况下,可以将 `inheritAttrs` 设置为 `false` 来禁用属性继承:
```js
MyComponent.inheritAttrs = false
```
函数式组件可以像普通组件一样被注册和使用。如果你将一个函数作为第一个参数传入 `h`,它将会被当作一个函数式组件来对待。
### 为函数式组件标注类型 {#typing-functional-components}
函数式组件可以根据它们是否有命名来标注类型。在单文件组件模板中,[Vue - Official 扩展](https://github.com/vuejs/language-tools)还支持对正确类型化的函数式组件进行类型检查。
**具名函数式组件**
```tsx
import type { SetupContext } from 'vue'
type FComponentProps = {
message: string
}
type Events = {
sendMessage(message: string): void
}
function FComponent(
props: FComponentProps,
context: SetupContext
) {
return (
)
}
FComponent.props = {
message: {
type: String,
required: true
}
}
FComponent.emits = {
sendMessage: (value: unknown) => typeof value === 'string'
}
```
**匿名函数式组件**
```tsx
import type { FunctionalComponent } from 'vue'
type FComponentProps = {
message: string
}
type Events = {
sendMessage(message: string): void
}
const FComponent: FunctionalComponent = (
props,
context
) => {
return (
)
}
FComponent.props = {
message: {
type: String,
required: true
}
}
FComponent.emits = {
sendMessage: (value) => typeof value === 'string'
}
```
---
---
url: /guide/extras/web-components.md
---
# Vue 与 Web Components {#vue-and-web-components}
[Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) 是一组 web 原生 API 的统称,允许开发者创建可复用的自定义元素 (custom elements)。
我们认为 Vue 和 Web Components 是互补的技术。Vue 为使用和创建自定义元素提供了出色的支持。无论你是将自定义元素集成到现有的 Vue 应用中,还是使用 Vue 来构建和分发自定义元素都很方便。
## 在 Vue 中使用自定义元素 {#using-custom-elements-in-vue}
Vue [在 Custom Elements Everywhere 测试中取得了 100% 的分数](https://custom-elements-everywhere.com/libraries/vue/results/results.html)。在 Vue 应用中使用自定义元素基本上与使用原生 HTML 元素的效果相同,但需要留意以下几点:
### 跳过组件解析 {#skipping-component-resolution}
默认情况下,Vue 会将任何非原生的 HTML 标签优先当作 Vue 组件处理,而将“渲染一个自定义元素”作为后备选项。这会在开发时导致 Vue 抛出一个“解析组件失败”的警告。要让 Vue 知晓特定元素应该被视为自定义元素并跳过组件解析,我们可以指定 [`compilerOptions.isCustomElement` 这个选项](/api/application#app-config-compileroptions)。
如果在开发 Vue 应用时进行了构建配置,则应该在构建配置中传递该选项,因为它是一个编译时选项。
#### 浏览器内编译时的示例配置 {#example-in-browser-config}
```js
// 仅在浏览器内编译时才会工作
// 如果使用了构建工具,请看下面的配置示例
app.config.compilerOptions.isCustomElement = (tag) => tag.includes('-')
```
#### Vite 示例配置 {#example-vite-config}
```js [vite.config.js]
import vue from '@vitejs/plugin-vue'
export default {
plugins: [
vue({
template: {
compilerOptions: {
// 将所有带短横线的标签名都视为自定义元素
isCustomElement: (tag) => tag.includes('-')
}
}
})
]
}
```
#### Vue CLI 示例配置 {#example-vue-cli-config}
```js [vue.config.js]
module.exports = {
chainWebpack: (config) => {
config.module
.rule('vue')
.use('vue-loader')
.tap((options) => ({
...options,
compilerOptions: {
// 将所有以 ion- 开头的标签都视为自定义元素
isCustomElement: (tag) => tag.startsWith('ion-')
}
}))
}
}
```
### 传递 DOM 属性 {#passing-dom-properties}
由于 DOM attribute 只能为字符串值,因此我们只能使用 DOM 对象的属性来传递复杂数据。当为自定义元素设置 props 时,Vue 3 将通过 `in` 操作符自动检查该属性是否已经存在于 DOM 对象上,并且在这个 key 存在时,更倾向于将值设置为一个 DOM 对象的属性。这意味着,在大多数情况下,如果自定义元素遵循[推荐的最佳实践](https://web.dev/custom-elements-best-practices/),你就不需要考虑这个问题。
然而,也会有一些特别的情况:必须将数据以一个 DOM 对象属性的方式传递,但该自定义元素无法正确地定义/反射这个属性 (因为 `in` 检查失败)。在这种情况下,你可以强制使用一个 `v-bind` 绑定、通过 `.prop` 修饰符来设置该 DOM 对象的属性:
```vue-html
```
## 使用 Vue 构建自定义元素 {#building-custom-elements-with-vue}
自定义元素的主要好处是,它们可以在使用任何框架,甚至是在不使用框架的场景下使用。当你面向的最终用户可能使用了不同的前端技术栈,或是当你希望将最终的应用与它使用的组件实现细节解耦时,它们会是理想的选择。
### defineCustomElement {#definecustomelement}
Vue 提供了一个和定义一般 Vue 组件几乎完全一致的 [`defineCustomElement`](/api/custom-elements#definecustomelement) 方法来支持创建自定义元素。这个方法接收的参数和 [`defineComponent`](/api/general#definecomponent) 完全相同。但它会返回一个继承自 `HTMLElement` 的自定义元素构造器:
```vue-html
```
```js
import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
// 这里是同平常一样的 Vue 组件选项
props: {},
emits: {},
template: `...`,
// defineCustomElement 特有的:注入进 shadow root 的 CSS
styles: [`/* inlined css */`]
})
// 注册自定义元素
// 注册之后,所有此页面中的 `` 标签
// 都会被升级
customElements.define('my-vue-element', MyVueElement)
// 你也可以编程式地实例化元素:
// (必须在注册之后)
document.body.appendChild(
new MyVueElement({
// 初始化 props (可选)
})
)
```
#### 生命周期 {#lifecycle}
* 当该元素的 [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks) 初次调用时,一个 Vue 自定义元素会在内部挂载一个 Vue 组件实例到它的 shadow root 上。
* 当此元素的 `disconnectedCallback` 被调用时,Vue 会在一个微任务后检查元素是否还留在文档中。
* 如果元素仍然在文档中,那么说明它是一次移动操作,组件实例将被保留;
* 如果该元素不再存在于文档中,那么说明这是一次移除操作,组件实例将被销毁。
#### Props {#props}
* 所有使用 `props` 选项声明了的 props 都会作为属性定义在该自定义元素上。Vue 会自动地、恰当地处理其作为 attribute 还是属性的反射。
* attribute 总是根据需要反射为相应的属性类型。
* 基础类型的属性值 (`string`,`boolean` 或 `number`) 会被反射为 attribute。
* 当它们被设为 attribute 时 (永远是字符串),Vue 也会自动将以 `Boolean` 或 `Number` 类型声明的 prop 转换为所期望的类型。比如下面这样的 props 声明:
```js
props: {
selected: Boolean,
index: Number
}
```
并以下面这样的方式使用自定义元素:
```vue-html
```
在组件中,`selected` 会被转换为 `true` (boolean 类型值) 而 `index` 会被转换为 `1` (number 类型值)。
#### 事件 {#events}
通过 `this.$emit` 或者 setup 中的 `emit` 触发的事件都会通过以 [CustomEvents](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#adding_custom_data_%E2%80%93_customevent) 的形式从自定义元素上派发。额外的事件参数 (payload) 将会被暴露为 CustomEvent 对象上的一个 `detail` 数组。
#### 插槽 {#slots}
在一个组件中,插槽将会照常使用 `` 渲染。然而,当使用最终的元素时,它只接受[原生插槽的语法](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots):
* 不支持[作用域插槽](/guide/components/slots#scoped-slots)。
* 当传递具名插槽时,应使用 `slot` attribute 而不是 `v-slot` 指令:
```vue-html
hello
```
#### 依赖注入 {#provide-inject}
[Provide / Inject API](/guide/components/provide-inject#provide-inject) 和[相应的组合式 API](/api/composition-api-dependency-injection#provide) 在 Vue 定义的自定义元素中都可以正常工作。但是请注意,依赖关系**只在自定义元素之间**起作用。例如一个 Vue 定义的自定义元素就无法注入一个由常规 Vue 组件所提供的属性。
#### 应用级配置 {#app-level-config}
你可以使用 `configureApp` 选项来配置 Vue 自定义元素的应用实例:
```js
defineCustomElement(MyComponent, {
configureApp(app) {
app.config.errorHandler = (err) => {
/* ... */
}
}
})
```
### 将单文件组件编译为自定义元素 {#sfc-as-custom-element}
`defineCustomElement` 也可以搭配 Vue 单文件组件 (SFC) 使用。但是,根据默认的工具链配置,SFC 中的 `
This could be e.g. documentation for the component.
```
## 相应语言块 {#language-blocks}
### `` {#template}
* 每个 `*.vue` 文件最多可以包含一个顶层 `` 块。
* 语块包裹的内容将会被提取、传递给 `@vue/compiler-dom`,预编译为 JavaScript 渲染函数,并附在导出的组件上作为其 `render` 选项。
### `
```
`lang` 在任意块上都能使用,比如我们可以在 `
```
注意对不同预处理器的集成会根据你所使用的工具链而有所不同,具体细节请查看相应的工具链文档来确认:
* [Vite](https://cn.vite.dev/guide/features.html#css-pre-processors)
* [Vue CLI](https://cli.vuejs.org/zh/guide/css.html#%E9%A2%84%E5%A4%84%E7%90%86%E5%99%A8)
* [webpack + vue-loader](https://vue-loader.vuejs.org/zh/guide/pre-processors.html#%E4%BD%BF%E7%94%A8%E9%A2%84%E5%A4%84%E7%90%86%E5%99%A8)
## `src` 导入 {#src-imports}
如果你更喜欢将 `*.vue` 组件分散到多个文件中,可以为一个语块使用 `src` 这个 attribute 来导入一个外部文件:
```vue
```
请注意 `src` 导入和 JS 模块导入遵循相同的路径解析规则,这意味着:
* 相对路径需要以 `./` 开头
* 你也可以从 npm 依赖中导入资源
```vue
```
`src` 导入对自定义语块也同样适用:
```vue
```
:::warning 注意
在 `src` 中使用别名时,不要以 `~` 开头,后面的任何内容都会被解释为模块请求。这意味着你可以引用 node 模块中的资源:
```vue
```
:::
## 注释 {#comments}
在每一个语块中你都可以按照相应语言 (HTML、CSS、JavaScript 和 Pug 等等) 的语法书写注释。对于顶层注释,请使用 HTML 的注释语法 ``
---
---
url: /api/sfc-script-setup.md
---
# \
```
里面的代码会被编译成组件 `setup()` 函数的内容。这意味着与普通的 `
```
import 导入的内容也会以同样的方式暴露。这意味着我们可以在模板表达式中直接使用导入的 helper 函数,而不需要通过 `methods` 选项来暴露它:
```vue
{{ capitalize('hello') }}
```
## 响应式 {#reactivity}
响应式状态需要明确使用[响应式 API](/api/reactivity-core) 来创建。和 `setup()` 函数的返回值一样,ref 在模板中使用的时候会自动解包:
```vue
```
## 使用组件 {#using-components}
`
```
这里 `MyComponent` 应当被理解为像是在引用一个变量。如果你使用过 JSX,此处的心智模型是类似的。其 kebab-case 格式的 `` 同样能在模板中使用——不过,我们强烈建议使用 PascalCase 格式以保持一致性。同时这也有助于区分原生的自定义元素。
### 动态组件 {#dynamic-components}
由于组件是通过变量引用而不是基于字符串组件名注册的,在 `
```
请注意组件是如何在三元表达式中被当做变量使用的。
### 递归组件 {#recursive-components}
一个单文件组件可以通过它的文件名被其自己所引用。例如:名为 `FooBar.vue` 的组件可以在其模板中用 `` 引用它自己。
请注意这种方式相比于导入的组件优先级更低。如果有具名的导入和组件自身推导的名字冲突了,可以为导入的组件添加别名:
```js
import { FooBar as FooBarChild } from './components'
```
### 命名空间组件 {#namespaced-components}
可以使用带 `.` 的组件标签,例如 `` 来引用嵌套在对象属性中的组件。这在需要从单个文件中导入多个组件的时候非常有用:
```vue
label
```
## 使用自定义指令 {#using-custom-directives}
全局注册的自定义指令将正常工作。本地的自定义指令在 `
This is a Heading
```
如果指令是从别处导入的,可以通过重命名来使其符合命名规范:
```vue
```
## defineProps() 和 defineEmits() {#defineprops-defineemits}
为了在声明 `props` 和 `emits` 选项时获得完整的类型推导支持,我们可以使用 `defineProps` 和 `defineEmits` API,它们将自动地在 `
```
* `defineProps` 和 `defineEmits` 都是只能在 `
```
```vue [Parent.vue]
```
另外,当搭配 `defineProps` 使用 `withDefaults` 时,对于可变引用类型 (如数组或对象) 的默认值,应在 `defineModel` 中用函数包装,以避免意外修改和外部副作用。
:::
### 修饰符和转换器 {#modifiers-and-transformers}
为了获取 `v-model` 指令使用的修饰符,我们可以像这样解构 `defineModel()` 的返回值:
```js
const [modelValue, modelModifiers] = defineModel()
// 对应 v-model.trim
if (modelModifiers.trim) {
// ...
}
```
当存在修饰符时,我们可能需要在读取或将其同步回父组件时对其值进行转换。我们可以通过使用 `get` 和 `set` 转换器选项来实现这一点:
```js
const [modelValue, modelModifiers] = defineModel({
// get() 省略了,因为这里不需要它
set(value) {
// 如果使用了 .trim 修饰符,则返回裁剪过后的值
if (modelModifiers.trim) {
return value.trim()
}
// 否则,原样返回
return value
}
})
```
### 在 TypeScript 中使用 {#usage-with-typescript}
与 `defineProps` 和 `defineEmits` 一样,`defineModel` 也可以接收类型参数来指定 model 值和修饰符的类型:
```ts
const modelValue = defineModel()
// ^? Ref
// 用带有选项的默认 model,设置 required 去掉了可能的 undefined 值
const modelValue = defineModel({ required: true })
// ^? Ref
const [modelValue, modifiers] = defineModel()
// ^? Record<'trim' | 'uppercase', true | undefined>
```
## defineExpose() {#defineexpose}
使用 `
```
当父组件通过模板引用的方式获取到当前组件的实例,获取到的实例会像这样 `{ a: number, b: number }` (ref 会和在普通实例中一样被自动解包)
## defineOptions() {#defineoptions}
* 仅在 3.3+ 中支持
这个宏可以用来直接在 `
```
* 这是一个宏定义,选项将会被提升到模块作用域中,无法访问 `
```
## `useSlots()` 和 `useAttrs()` {#useslots-useattrs}
在 `
```
`useSlots` 和 `useAttrs` 是真实的运行时函数,它们的返回值分别与 `setupContext.slots` 和 `setupContext.attrs` 等价。它们同样也能在普通的组合式 API 中使用。
## 与普通的 `
```
在同一组件中将 `
```
另外,await 的表达式会自动编译成在 `await` 之后保留当前组件实例上下文的格式。
:::warning 注意
`async setup()` 必须与 [`Suspense`](/guide/built-ins/suspense.html) 组合使用,该特性目前仍处于实验阶段。我们计划在未来的版本中完成该特性并编写文档——但如果你现在就感兴趣,可以参考其[测试](https://github.com/vuejs/core/blob/main/packages/runtime-core/__tests__/components/Suspense.spec.ts)来了解其工作方式。
:::
## 导入语句 {#imports-statements}
Vue 中的导入语句遵循 [ECMAScript 模块规范](https://nodejs.org/api/esm.html)。
此外,你还可以使用构建工具配置中定义的别名:
```vue
```
## 泛型 {#generics}
可以使用 `
```
`generic` 的值与 TypeScript 中位于 `<...>` 之间的参数列表完全相同。例如,你可以使用多个参数,`extends` 约束,默认类型和引用导入的类型:
```vue
```
当无法自动推断泛型组件的具体类型时,可使用指令 `@vue-generic` 来显式指定:
```vue
```
为了在 `ref` 中使用泛型组件的引用,你需要使用 [`vue-component-type-helpers`](https://www.npmjs.com/package/vue-component-type-helpers) 库,因为 `InstanceType` 在这种场景下不起作用。
```vue
red
```
## CSS 中的 `v-bind()` {#v-bind-in-css}
单文件组件的 `
```
这个语法同样也适用于 [`
hello
```
实际的值会被编译成哈希化的 CSS 自定义属性,因此 CSS 本身仍然是静态的。自定义属性会通过内联样式的方式应用到组件的根元素上,并且在源值变更的时候响应式地更新。
---
---
url: /api/custom-elements.md
---
# 自定义元素 API {#custom-elements-api}
## defineCustomElement() {#definecustomelement}
此方法接受的参数与 [`defineComponent`](/api/general.html#definecomponent) 相同,但返回一个原生[自定义元素](https://developer.mozilla.org/zh-CN/docs/Web/Web_Components/Using_custom_elements)类构造函数。
* **类型**
```ts
function defineCustomElement(
component:
| (ComponentOptions & CustomElementsOptions)
| ComponentOptions['setup'],
options?: CustomElementsOptions
): {
new (props?: object): HTMLElement
}
interface CustomElementsOptions {
styles?: string[]
// 以下选项在 3.5+ 版本中支持
configureApp?: (app: App) => void
shadowRoot?: boolean
nonce?: string
}
```
> 类型为简化版,便于阅读。
* **详情**
除了常规的组件选项,`defineCustomElement()` 还支持一系列特定于自定义元素的选项:
* **`styles`**:一个内联 CSS 字符串数组,用于提供应注入元素 shadow root 的 CSS。
* **`configureApp`** :一个函数,可用于配置自定义元素的 Vue 应用实例。
* **`shadowRoot`** :`boolean`,默认为 `true`。设置为 `false` 以在不带 shadow root 的情况下渲染自定义元素。这意味着自定义元素单文件组件中的 `
```
```vue-html
```
```vue-html
```
```vue-html
```
---
---
url: /style-guide/rules-strongly-recommended.md
---
# Priority B Rules: Strongly Recommended {#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 {#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.
```js
app.component('TodoList', {
// ...
})
app.component('TodoItem', {
// ...
})
```
```
components/
|- TodoList.js
|- TodoItem.js
```
```
components/
|- TodoList.vue
|- TodoItem.vue
```
## Single-file component filename casing {#single-file-component-filename-casing}
**Filenames of [Single-File Components](/guide/scaling-up/sfc) 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-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`.**
::: details 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](https://pinia.vuejs.org/) 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:
```js
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 {#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.
::: details 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 {#order-of-words-in-component-names}
**Component names should start with the highest-level (often most general) words and end with descriptive modifying words.**
::: details 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 {#self-closing-components}
**Components with no content should be self-closing in [Single-File Components](/guide/scaling-up/sfc), string templates, and [JSX](/guide/extras/render-function#jsx-tsx) - 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](https://html.spec.whatwg.org/multipage/syntax.html#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.
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
```
## Component name casing in templates {#component-name-casing-in-templates}
**In most projects, component names should always be PascalCase in [Single-File Components](/guide/scaling-up/sfc) 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.
* `` is more visually distinct from a single-word HTML element than ``, 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.**
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
```
OR
```vue-html
```
## Component name casing in JS/JSX {#component-name-casing-in-js-jsx}
**Component names in JS/[JSX](/guide/extras/render-function#jsx-tsx) should always be PascalCase, though they may be kebab-case inside strings for simpler applications that only use global component registration through `app.component`.**
::: details 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](#component-name-casing-in-templates).
:::
```js
app.component('myComponent', {
// ...
})
```
```js
import myComponent from './MyComponent.vue'
```
```js
export default {
name: 'myComponent'
// ...
}
```
```js
export default {
name: 'my-component'
// ...
}
```
```js
app.component('MyComponent', {
// ...
})
```
```js
app.component('my-component', {
// ...
})
```
```js
import MyComponent from './MyComponent.vue'
```
```js
export default {
name: 'MyComponent'
// ...
}
```
## Full-word component names {#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-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](/guide/extras/render-function#jsx-tsx) 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**
```js
props: {
'greeting-text': String
}
```
```js
const props = defineProps({
'greeting-text': String
})
```
```vue-html
// for in-DOM templates
```
```js
props: {
greetingText: String
}
```
```js
const props = defineProps({
greetingText: String
})
```
```vue-html
// 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
// or
```
```vue-html
// for in-DOM templates
```
## Multi-attribute elements {#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](/guide/extras/render-function#jsx-tsx) deserve the same consideration.
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
```
## Simple expressions in templates {#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.
```vue-html
{{
fullName.split(' ').map((word) => {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
```
```vue-html
{{ normalizedFullName }}
```
```js
// 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(' ')
}
}
```
```js
// 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 {#simple-computed-properties}
**Complex computed properties should be split into as many simpler properties as possible.**
::: details 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.
:::
```js
computed: {
price() {
const basePrice = this.manufactureCost / (1 - this.profitMargin)
return (
basePrice -
basePrice * (this.discountPercent || 0)
)
}
}
```
```js
const price = computed(() => {
const basePrice = manufactureCost.value / (1 - profitMargin.value)
return basePrice - basePrice * (discountPercent.value || 0)
})
```
```js
computed: {
basePrice() {
return this.manufactureCost / (1 - this.profitMargin)
},
discount() {
return this.basePrice * (this.discountPercent || 0)
},
finalPrice() {
return this.basePrice - this.discount
}
}
```
```js
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 {#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.
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
```
## Directive shorthands {#directive-shorthands}
**Directive shorthands (`:` for `v-bind:`, `@` for `v-on:` and `#` for `v-slot`) should be used always or never.**
```vue-html
```
```vue-html
```
```vue-html
Here might be a page title
Here's some contact info
```
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
```
```vue-html
Here might be a page title
Here's some contact info
```
```vue-html
Here might be a page title
Here's some contact info
```
---
---
url: /style-guide/rules-recommended.md
---
# Priority C Rules: Recommended {#priority-c-rules-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:
1. Train your brain to more easily parse most of the community code you encounter
2. Be able to copy and paste most community code examples without modification
3. Often find new hires are already accustomed to your preferred coding style, at least in regards to Vue
## Component/instance options order {#component-instance-options-order}
**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.
1. **Global Awareness** (requires knowledge beyond the component)
* `name`
2. **Template Compiler Options** (changes the way templates are compiled)
* `compilerOptions`
3. **Template Dependencies** (assets used in the template)
* `components`
* `directives`
4. **Composition** (merges properties into the options)
* `extends`
* `mixins`
* `provide`/`inject`
5. **Interface** (the interface to the component)
* `inheritAttrs`
* `props`
* `emits`
* `expose`
6. **Composition API** (the entry point for using the Composition API)
* `setup`
7. **Local State** (local reactive properties)
* `data`
* `computed`
8. **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`
* `serverPrefetch` (SSR only)
9. **Non-Reactive Properties** (instance properties independent of the reactivity system)
* `methods`
10. **Rendering** (the declarative description of the component output)
* `template`/`render`
## Element attribute order {#element-attribute-order}
**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.
1. **Definition** (provides the component options)
* `is`
2. **List Rendering** (creates multiple variations of the same element)
* `v-for`
3. **Conditionals** (whether the element is rendered/shown)
* `v-if`
* `v-else-if`
* `v-else`
* `v-show`
* `v-cloak`
4. **Render Modifiers** (changes the way the element renders)
* `v-pre`
* `v-once`
5. **Global Awareness** (requires knowledge beyond the component)
* `id`
6. **Unique Attributes** (attributes that require unique values)
* `ref`
* `key`
7. **Two-Way Binding** (combining binding and events)
* `v-model`
8. **Other Attributes** (all unspecified bound & unbound attributes)
9. **Events** (component event listeners)
* `v-on`
10. **Content** (overrides the content of the element)
* `v-html`
* `v-text`
## Empty lines in component/instance options {#empty-lines-in-component-instance-options}
**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.
```js
props: {
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
},
computed: {
formattedValue() {
// ...
},
inputClasses() {
// ...
}
}
```
```js
// 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() {
// ...
}
}
```
```js
defineProps({
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
})
const formattedValue = computed(() => {
// ...
})
const inputClasses = computed(() => {
// ...
})
```
```js
defineProps({
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
})
const formattedValue = computed(() => {
// ...
})
const inputClasses = computed(() => {
// ...
})
```
## Single-file component top-level element order {#single-file-component-top-level-element-order}
**[Single-File Components](/guide/scaling-up/sfc) should always order `
...
```
```vue-html [ComponentA.vue]
...
```
```vue-html [ComponentB.vue]
...
```
```vue-html [ComponentA.vue]
...
```
```vue-html [ComponentB.vue]
...
```
or
```vue-html [ComponentA.vue]
...
```
```vue-html [ComponentB.vue]
...
```
---
---
url: /style-guide/rules-use-with-caution.md
---
# Priority D Rules: Use with Caution {#priority-d-rules-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.
## Element selectors with `scoped` {#element-selectors-with-scoped}
**Element selectors should be avoided with `scoped`.**
Prefer class selectors over element selectors in `scoped` styles, because large numbers of element selectors are slow.
::: details 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 (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.
:::
```vue-html
```
```vue-html
```
## Implicit parent-child communication {#implicit-parent-child-communication}
**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).
```js
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
template: ''
})
```
```js
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: `
{{ todo.text }}
`
})
```
```js
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
emits: ['input'],
template: `
`
})
```
```js
app.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
emits: ['delete'],
template: `
{{ todo.text }}
`
})
```
```vue
```
```vue
{{ todo.text }}
```
```vue
```
```vue
{{ todo.text }}
```
---
---
url: /api.md
---
---
---
url: /style-guide/PLEADE_DO_NOT_TRANSLATE.md
---
# Please DO NOT Translate
Please do not translate the style guide docs until further consideration since:
1. The English version still needs to be revamped.
2. Currently there is no entry link on the doc site.
Thanks.
Ref: https://github.com/vuejs-translations/docs-zh-cn/pull/237#issuecomment-1148418220
---
---
url: /guide/extras/reactivity-transform.md
---
# 响应性语法糖 {#reactivity-transform}
:::danger 已移除的实验性功能
响应性语法糖曾经是一个实验性功能,且已在最新的 3.4 版本中被移除,请阅读[废弃原因](https://github.com/vuejs/rfcs/discussions/369#discussioncomment-5059028)。
如果仍然打算使用它,你现在可以使用 [Vue Macros](https://vue-macros.sxzz.moe/features/reactivity-transform.html) 插件。
:::
:::tip 组合式 API 特有
响应性语法糖是组合式 API 特有的功能,且必须通过构建步骤使用。
:::
## ref vs. 响应式变量 {#refs-vs-reactive-variables}
自从引入组合式 API 的概念以来,一个主要的未解决的问题就是 ref 和响应式对象到底用哪个。响应式对象存在解构丢失响应性的问题,而 ref 需要到处使用 `.value` 则感觉很繁琐,并且在没有类型系统的帮助时很容易漏掉 `.value`。
[Vue 的响应性语法糖](https://github.com/vuejs/core/tree/main/packages/reactivity-transform)是一个编译时的转换步骤,让我们可以像这样书写代码:
```vue
```
这里的这个 `$ref()` 方法是一个**编译时的宏命令**:它不是一个真实的、在运行时会调用的方法。而是用作 Vue 编译器的标记,表明最终的 `count` 变量需要是一个**响应式变量**。
响应式的变量可以像普通变量那样被访问和重新赋值,但这些操作在编译后都会变为带 `.value` 的 ref。比如上面例子中 `
```
上面的代码将被编译成下面这样的运行时声明:
```js
export default {
props: {
msg: { type: String, required: true },
count: { type: Number, default: 1 },
foo: String
},
setup(props) {
watchEffect(() => {
console.log(props.msg, props.count, props.foo)
})
}
}
```
## 保持在函数间传递时的响应性 {#retaining-reactivity-across-function-boundaries}
虽然响应式变量使我们可以不再受 `.value` 的困扰,但它也使得我们在函数间传递响应式变量时可能造成“响应性丢失”的问题。这可能在以下两种场景中出现:
### 以参数形式传入函数 {#passing-into-function-as-argument}
假设有一个期望接收一个 ref 对象为参数的函数:
```ts
function trackChange(x: Ref) {
watch(x, (x) => {
console.log('x 改变了!')
})
}
let count = $ref(0)
trackChange(count) // 无效!
```
上面的例子不会正常工作,因为代码被编译成了这样:
```ts
let count = ref(0)
trackChange(count.value)
```
这里的 `count.value` 是以一个 number 类型值的形式传入,然而 `trackChange` 期望接收的是一个真正的 ref。要解决这个问题,可以在将 `count` 作为参数传入之前,用 `$$()` 包装:
```diff
let count = $ref(0)
- trackChange(count)
+ trackChange($$(count))
```
上面的代码将被编译成:
```js
import { ref } from 'vue'
let count = ref(0)
trackChange(count)
```
我们可以看到,`$$()` 的效果就像是一个**转义标识**:`$$()` 中的响应式变量不会追加上 `.value`。
### 作为函数返回值 {#returning-inside-function-scope}
如果将响应式变量直接放在返回值表达式中会丢失掉响应性:
```ts
function useMouse() {
let x = $ref(0)
let y = $ref(0)
// 监听 mousemove 事件
// 不起效!
return {
x,
y
}
}
```
上面的语句将被翻译为:
```ts
return {
x: x.value,
y: y.value
}
```
为了保持响应性,我们需要返回的是真正的 ref,而不是返回时 ref 内的值。
我们还是可以使用 `$$()` 来解决这个问题。在这个例子中,`$$()` 可以直接用在要返回的对象上,`$$()` 调用时任何对响应式变量的引用都会保留为对相应 ref 的引用:
```ts
function useMouse() {
let x = $ref(0)
let y = $ref(0)
// 监听 mousemove 事件
// 修改后起效
return $$({
x,
y
})
}
```
### 在已解构的 props 上使用 `$$()` {#using-on-destructured-props}
`$$()` 也适用于已解构的 props,因为它们也是响应式的变量。编译器会高效地通过 `toRef` 来做转换:
```ts
const { count } = defineProps<{ count: number }>()
passAsRef($$(count))
```
编译结果为:
```js
setup(props) {
const __props_count = toRef(props, 'count')
passAsRef(__props_count)
}
```
## TypeScript 集成 {#typescript-integration}
Vue 为这些宏函数都提供了类型声明 (全局可用),因此类型推导都会符合预期。它与标准的 TypeScript 语义没有不兼容之处,因此它的语法可以与所有现有的工具兼容。
这也意味着这些宏函数在任何 JS / TS 文件中都是合法的,不是仅能在 Vue 单文件组件中使用。
因为这些宏函数都是全局可用的,它们的类型需要被显式地引用 (例如,在 `env.d.ts` 文件中):
```ts
///
```
若你是从 `vue/macros` 中显式引入宏函数时,则不需要像这样全局声明。
## 显式启用 {#explicit-opt-in}
:::danger Core 不再支持
以下内容仅适用于 Vue 3.3 及以下版本。Vue core 3.4 及以上版本和 `@vitejs/plugin-vue` 5.0 及以上版本已经将其移除。如需继续使用,请迁移至 [Vue Macros](https://vue-macros.sxzz.moe/features/reactivity-transform.html)。
:::
### Vite {#vite}
* 需要 `@vitejs/plugin-vue@>=2.0.0`
* 应用于单文件组件和 js(x)/ts(x) 文件。在执行转换之前,会对文件进行快速的使用检查,因此不使用宏的文件不会有性能损失。
* 注意 `reactivityTransform` 现在是一个插件的顶层选项,而不再是位于 `script.refSugar` 之中了,因为它不仅仅只对单文件组件起效。
```js [vite.config.js]
export default {
plugins: [
vue({
reactivityTransform: true
})
]
}
```
### `vue-cli` {#vue-cli}
* 目前仅对单文件组件起效
* 需要 `vue-loader@>=17.0.0`
```js [vue.config.js]
module.exports = {
chainWebpack: (config) => {
config.module
.rule('vue')
.use('vue-loader')
.tap((options) => {
return {
...options,
reactivityTransform: true
}
})
}
}
```
### 仅用 `webpack` + `vue-loader` {#plain-webpack-vue-loader}
* 目前仅对单文件组件起效
* 需要 `vue-loader@>=17.0.0`
```js [webpack.config.js]
module.exports = {
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
reactivityTransform: true
}
}
]
}
}
```
---
---
url: /translations.md
---
# 多语言及翻译 {#translations}
## 多语言版本 {#available-languages}
* [English / 英语](https://vuejs.org/) \[[源码](https://github.com/vuejs/docs)]
* [简体中文](https://cn.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-zh-cn)]
* [日本語 / 日语](https://ja.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-ja)]
* [Українська / 乌克兰语](https://ua.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-uk)]
* [Français / 法语](https://fr.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-fr)]
* [Deutsch / 德语](https://de.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-de)]
* [한국어 / 韩语](https://ko.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-ko)]
* [Português / 葡萄牙语](https://pt.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-pt)]
* [বাংলা / 孟加拉语](https://bn.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-bn)]
* [Italiano / 意大利语](https://it.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-it)]
* [فارسی / 波斯语](https://fa.vuejs.org) \[[源码](https://github.com/vuejs-translations/docs-fa)]
* [Русский / 俄罗斯语](https://ru.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-ru)]
* [Čeština / 捷克语](https://cs.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-cs)]
* [繁體中文 / 繁体中文](https://zh-hk.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-zh-hk)]
* [Polski / 波兰语](https://pl.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-pl)]
## 翻译中的语言 {#work-in-progress-languages}
* [العربية / 阿拉伯语](https://ar.vuejs.org/) \[[源码](https://github.com/vuejs-translations/docs-ar)]
* [Español / 西班牙语](https://vue3-spanish-docs.netlify.app/) \[[源码](https://github.com/icarusgk/vuejs-spanish-docs)]
## 贡献翻译 {#contributing-to-translations}
* [Deutsch / 德语](https://de.vuejs.org/) \[[source](https://github.com/vuejs-translations/docs-de)]
## 启动新的翻译 {#starting-a-new-translation}
近期 Vue 的文档经历了一次大的版本升级,所以其他语言的翻译版本仍不可用或进行中。
我们希望通过社区的努力提供更多语言的翻译。这些工作是在 [vuejs-translations](https://github.com/vuejs-translations/) GitHub 组织进行的。如果你对此感兴趣,请查看[翻译指南](https://github.com/vuejs-translations/guidelines/blob/main/README.md)。
---
---
url: /about/faq.md
---
# 常见问题 {#frequently-asked-questions}
## 谁在维护 Vue? {#who-maintains-vue}
Vue 是一个独立的社区驱动的项目。它是由[尤雨溪](https://x.com/evanyou)在 2014 年作为其个人项目创建的。今天,Vue 由[来自世界各地的全职成员和志愿者组成的团队](/about/team)积极活跃地维护着,并由尤雨溪担任项目负责人。你可以在[这部纪录片](https://www.youtube.com/watch?v=OrxmtDw4pVI)中了解更多关于 Vue 的故事。
自 2016 年以来,Vue 的发展主要是通过赞助来保障的,我们在财务上是可持续的。如果你或你的企业从 Vue 中受益,请考虑[赞助](/sponsor/)我们,以支持 Vue 的发展!
## Vue 2 和 Vue 3 之间的区别是什么? {#what-s-the-difference-between-vue-2-and-vue-3}
Vue 3 是 Vue 当前的最新主版本。它包含了一些 Vue 2 中没有的新特性 (比如 Teleport、Suspense,以及多根元素模板)。同时它也包含了一些与 Vue 2 非兼容性的变更。细节文档请参考 [Vue 3 迁移指南](https://v3-migration.vuejs.org/zh/)。
尽管存在差异,但大多数 Vue API 在两个大版本之间是共享的,所以你的大部分 Vue 2 知识将继续在 Vue 3 中发挥作用。需要注意的是,组合式 API 原本是一个 Vue 3 独有的特性,但目前已兼容至 Vue 2 且在 [Vue 2.7](https://github.com/vuejs/vue/blob/main/CHANGELOG.md#270-2022-07-01) 中可用。
总的来说,Vue 3 提供了更小的包体积、更好的性能、更好的可扩展性和更好的 TypeScript/IDE 支持。如果你现在要开始一个新项目,我们推荐你选择 Vue 3。但也仍然存在一些考虑使用 Vue 2 的理由:
* 你需要支持 IE11。Vue 3 用到了一些 IE11 不支持的现代 JavaScript 特性。
如果你打算将现有的 Vue 2 应用迁移到 Vue 3,请查阅[迁移指南](https://v3-migration.vuejs.org/zh/)。
## Vue 2 仍在维护吗? {#is-vue-2-still-supported}
Vue 2 在 2022 年 6 月发布了最后一个小版本 (2.7)。目前 Vue 2 已经进入维护模式:它将不再提供新特性,但从 2.7 的发布日期开始的 18 个月内,它将继续针对重大错误修复和安全更新进行发布。这意味着 **Vue 2 已在 2023 年 12 月 31 日到达它的截止维护日期**。
我们相信这为大多数的生态系统提供了足够长的时间来迁移到 Vue 3。然而,我们也理解可能会有无法在此时间轴上升级的团队或项目仍需满足其安全及合规需求。我们正在与业内专家合作为有这种需求的团队提供 Vue 2 的扩展支持——如果您的团队预期在 2023 年底之后仍然需要使用 Vue 2,请确保提前计划,详见 [Vue 2 延长 LTS](https://v2.vuejs.org/lts/)。
## Vue 使用什么开源协议? {#what-license-does-vue-use}
Vue 是完全免费的开源项目,且基于 [MIT License](https://opensource.org/licenses/MIT) 发布。
## Vue 支持哪些浏览器? {#what-browsers-does-vue-support}
最新版本的 Vue (3.x) 只支持[原生支持 ES2016 的浏览器](https://caniuse.com/es2016)。这并不包括 IE11。Vue 3.x 使用的 ES2016 功能无法在旧版本的浏览器中进行兼容,如果你需要支持旧版本的浏览器,请使用 Vue 2.x 替代。
## Vue 可靠吗? {#is-vue-reliable}
Vue 是一个成熟的、经历了无数实战考验的框架。它是目前生产环境中使用最广泛的 JavaScript 框架之一,在全球拥有超过 150 万用户,并且在 npm 上的月下载量超过 1000 万次。
Vue 被世界各地知名且多元的组织在生产环境中使用,包括 Wikimedia 基金会、美国宇航局、苹果、谷歌、微软、GitLab、Zoom、腾讯、微博、哔哩哔哩、快手等等。
## Vue 速度快吗? {#is-vue-fast}
Vue 3 是性能最强的主流前端框架之一,可以轻松处理大多数 web 应用的场景,并且几乎不需要手动优化。
跑分方面,Vue 在 [js-framework-benchmark](https://krausest.github.io/js-framework-benchmark/current.html) 中的表现比 React 和 Angular 要好得多。在该基准测试中,它还与一些生产环境下最快级别的非虚拟 DOM 框架并驾齐驱。
请注意,像上面这样的跑分的侧重点在于原始渲染性能在特定情况下的优化,因此不能完全代表真实世界的性能结果。如果你更关心页面加载性能,欢迎用 [WebPageTest](https://www.webpagetest.org/lighthouse) 或是 [PageSpeed Insights](https://pagespeed.web.dev/) 来测试本站。本文档站是一个完全由 Vue 本身构建,通过静态生成预渲染,并在客户端进行 hydration 的单页应用。它在模拟 4 倍 CPU 降速的 Moto G4 + 低速 4G 网络的情况下依然能获得 100 分的性能得分。
你可以在[渲染机制](/guide/extras/rendering-mechanism)章节了解更多关于 Vue 如何自动优化运行时性能的信息,也可以在[性能优化指南](/guide/best-practices/performance)中了解如何在特别苛刻的情况下优化 Vue 应用。
## Vue 体积小吗? {#is-vue-lightweight}
当你通过构建工具使用时,Vue 的许多 API 都是可以[“tree-shake”](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking)的。例如,如果你不使用内置的 `` 组件,它就不会被包含在最终的生产环境包里。
对于一个 Vue 的最少 API 使用的 hello world 应用来说,配合最小化和 brotli 压缩,其基线大小只有 **16kb** 左右。但实际的应用大小取决于你使用了多少框架的可选特性。在极端情况下,如果一个应用使用了 Vue 提供的每一个特性,那么总的运行时大小大约为 **27kb**。
如果不通过构建工具使用 Vue,我们不仅失去了 tree-shaking,而且还必须将模板编译器加载到浏览器。这就使包体积增大到了 **41kb** 左右。因此,如果你为了渐进式增强在没有构建步骤的情况下使用 Vue,则可以考虑使用 [petite-vue](https://github.com/vuejs/petite-vue) (仅 **6kb**) 来代替。
一些诸如 Svelte 的框架使用了一种为单个组件产生极轻量级输出的编译策略。然而,[我们的研究](https://github.com/yyx990803/vue-svelte-size-analysis)表明,包大小的差异在很大程度上取决于应用中的组件数量。虽然 Vue 的基线大小更重,但它生成的每个组件的代码更少。在现实的场景中,Vue 应用很可能最终会更轻。
## Vue 能胜任大规模场景吗? {#does-vue-scale}
是的。尽管有一种误解是 Vue 只适用于简单的场景,但其实 Vue 完全有能力处理大规模的应用:
* [单文件组件](/guide/scaling-up/sfc)提供了一个模块化的开发模型,让应用的不同部分能够被隔离开发。
* [组合式 API](/guide/reusability/composables) 提供一流的 TypeScript 集成,并为组织、提取和重用复杂逻辑提供了简洁的模式。
* [全面的工具链支持](/guide/scaling-up/tooling)使得开发体验在应用增长的过程中依然可以保持平滑。
* 较低的入门门槛和优秀的文档能够显著降低新手开发者的入职和培训成本。
## 我可以为 Vue 做贡献吗? {#how-do-i-contribute-to-vue}
非常欢迎!请阅读我们的[社区指南](/about/community-guide)。
## 我应该使用选项式 API 还是组合式 API? {#should-i-use-options-api-or-composition-api}
如果你是 Vue 的新手,我们在[这里](/guide/introduction#which-to-choose)提供了一个两者之间宏观的比较。
如果你过去使用过选项式 API 且正在评估组合式 API,可以查阅[组合式 API 常见问题](/guide/extras/composition-api-faq)。
## 用 Vue 的时候应该选 JS 还是 TS? {#should-i-use-javascript-or-typescript-with-vue}
虽然 Vue 本身是用 TypeScript 实现的,并提供一流的 TypeScript 支持,但它并不强制要求用户使用 TypeScript。
在向 Vue 添加新特性时,对 TypeScript 的支持是一个重要的考虑因素。即使你自己不使用 TypeScript,考虑了 TypeScript 支持的 API 设计也通常更容易被 IDE 和静态分析工具分析,因此这对大家都有好处。Vue 的 API 设计也尽可能在 JavaScript 和 TypeScript 中以相同的方式工作。
选用 TypeScript 会涉及在上手复杂性和长期可维护性收益之间作出权衡。这种权衡是否合理取决于你的团队背景和项目规模,但 Vue 并不会真正成为影响这一决定的因素。
## Vue 相比于 Web Components 究竟如何? {#how-does-vue-compare-to-web-components}
Vue 是在 Web Components 出现之前被创建的,Vue 在某些方面的设计 (例如插槽) 受到了 Web Components 模型的启发。
Web Components 规范相对底层一些,因为它们是以自定义元素为中心的。作为一个框架,Vue 解决了更多上层的问题,如高效的 DOM 渲染、响应式状态管理、工具链、客户端路由和服务器端渲染等。
Vue 完全支持在 Vue 组件中使用原生自定义元素,也支持将 Vue 组件导出为原生自定义元素——请参阅 [Vue 和 Web Components 指南](/guide/extras/web-components)以了解更多细节。
---
---
url: /tutorial.md
---
---
---
url: /glossary.md
---
# 术语表 {#glossary}
本术语表旨在为一些在讨论 Vue 时常用的技术术语的含义提供指导。其目的在于*描述*术语的常见用法,而不是*规定*它们必须如何使用。在不同的上下文中,一些术语的含义可能会有细微的差别。
\[\[TOC]]
## 异步组件 (async component) {#async-component}
*异步组件*是为另一个组件提供的包装器,来让被包装的组件可以进行懒加载。这通常用作减少构建后的 `.js` 文件大小的一种方式,通过将它们拆分为较小的块来按需加载。
Vue Router 也有类似的功能,用于[路由懒加载](https://router.vuejs.org/zh/guide/advanced/lazy-loading.html),但这并不是通过 Vue 的异步组件功能实现的。
详见:
* [指南 - 异步组件](/guide/components/async.html)
## 编译器宏 (compiler macro) {#compiler-macro}
*编译器宏*是一种特殊的代码,由编译器处理并转换为其他东西。它们实际上是一种更巧妙的字符串替换形式。
Vue 的[单文件组件](#single-file-component)编译器支持各种宏,例如 `defineProps()`、`defineEmits()` 和 `defineExpose()`。这些宏有意设计得像是普通的 JavaScript 函数,以便它们可以利用 JavaScript / TypeScript 中的相同解析器和类型推断工具。然而,它们不是在浏览器中运行的实际函数。这些特殊字符串会被编译器检测到并替换为实际真正运行的 JavaScript 代码。
宏在使用上有一些不适用于普通 JavaScript 代码的限制。例如,你可能认为 `const dp = defineProps` 会为 `defineProps` 创建一个别名,但实际上它会导致错误。相同的限制也存在于传入 `defineProps()` 的值,因为“参数”必须由编译器处理,而不是在运行时。
详见:
* [`