Skip to content
This repository was archived by the owner on Aug 8, 2022. It is now read-only.

Commit ed61d6a

Browse files
arronKlerzouyawei.feveaba
authored
docs: translate sfc-script-setup.md (#652)
* docs: translate sfc-script-setup.md * docs: format sfc-script-setup.md * fix(sfc-script-setup.md): i.e. translation error * docs: update some translation * docs: use 自动展开 instead 自动拆箱 * Apply suggestions from code review unwrap 翻译为自动解包 Co-authored-by: Godpu <[email protected]> Co-authored-by: zouyawei.fe <[email protected]> Co-authored-by: Godpu <[email protected]>
1 parent 84ed5a2 commit ed61d6a

File tree

1 file changed

+70
-71
lines changed

1 file changed

+70
-71
lines changed

src/api/sfc-script-setup.md

Lines changed: 70 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,37 @@
22
sidebarDepth: 1
33
---
44

5-
<!-- TODO: translation -->
6-
# SFC `<script setup>`
5+
# 单文件组件 `<script setup>`
76

8-
`<script setup>` is a compile-time syntactic sugar for using [Composition API](/api/composition-api.html) inside Single File Components (SFCs). It is the recommended syntax if you are using both SFCs and Composition API. It provides a number of advantages over the normal `<script>` syntax:
7+
`<script setup>` 是在单文件组件 (SFC) 中使用[组合式 API](/api/composition-api.html) 的编译时语法糖。相比于普通的 `<script>` 语法,它具有更多优势:
98

10-
- More succinct code with less boilerplate
11-
- Ability to declare props and emitted events using pure TypeScript
12-
- Better runtime performance (the template is compiled into a render function in the same scope, without an intermediate proxy)
13-
- Better IDE type-inference performance (less work for the language server to extract types from code)
9+
- 更少的样板内容,更简洁的代码。
10+
- 能够使用纯 Typescript 声明 props 和发出事件。
11+
- 更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。
12+
- 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。
1413

15-
## Basic Syntax
14+
## 基本语法
1615

17-
To opt-in to the syntax, add the `setup` attribute to the `<script>` block:
16+
要选择加入这个语法,需要将 `setup` attribute 添加到 `<script>` 代码块上:
1817

1918
```vue
2019
<script setup>
2120
console.log('hello script setup')
2221
</script>
2322
```
2423

25-
The code inside is compiled as the content of the component's `setup()` function. This means that unlike normal `<script>`, which only executes once when the component is first imported, code inside `<script setup>` will **execute every time an instance of the component is created**.
24+
里面的代码会被编译成组件 `setup()` 函数的内容。这意味着与普通的 `<script>` 只在组件被首次引入的时候执行一次不同,`<script setup>` 中的代码会在**每次组件实例被创建的时候执行**
2625

27-
### Top-level bindings are exposed to template
26+
### 顶层的绑定会被暴露给模板
2827

29-
When using `<script setup>`, any top-level bindings (including variables, function declarations, and imports) declared inside `<script setup>` are directly usable in the template:
28+
当使用 `<script setup>` 的时候,任何在 `<script setup>` 声明的顶层的绑定 (包括变量,函数声明,以及 import 引入的内容) 都能在模板中直接使用:
3029

3130
```vue
3231
<script setup>
33-
// variable
32+
// 变量
3433
const msg = 'Hello!'
3534
36-
// functions
35+
// 函数
3736
function log() {
3837
console.log(msg)
3938
}
@@ -44,7 +43,7 @@ function log() {
4443
</template>
4544
```
4645

47-
Imports are exposed in the same fashion. This means you can directly use an imported helper function in template expressions without having to expose it via the `methods` option:
46+
import 导入的内容也会以同样的方式暴露。意味着可以在模板表达式中直接使用导入的 helper 函数,并不需要通过 `methods` 选项来暴露它:
4847

4948
```vue
5049
<script setup>
@@ -56,9 +55,9 @@ import { capitalize } from './helpers'
5655
</template>
5756
```
5857

59-
## Reactivity
58+
## 响应式
6059

61-
Reactive state needs to be explicitly created using [Reactivity APIs](/api/basic-reactivity.html). Similar to values returned from a `setup()` function, refs are automatically unwrapped when referenced in templates:
60+
响应式状态需要明确使用[响应式 APIs](/api/basic-reactivity.html) 来创建。和从 `setup()` 函数中返回值一样,ref 值在模板中使用的时候会自动解包:
6261

6362
```vue
6463
<script setup>
@@ -72,9 +71,9 @@ const count = ref(0)
7271
</template>
7372
```
7473

75-
## Using Components
74+
## 使用组件
7675

77-
Values in the scope of `<script setup>` can also be used directly as custom component tag names:
76+
`<script setup>` 范围里的值也能被直接作为自定义组件的标签名称使用:
7877

7978
```vue
8079
<script setup>
@@ -86,11 +85,11 @@ import MyComponent from './MyComponent.vue'
8685
</template>
8786
```
8887

89-
Think of `MyComponent` as being referenced as a variable. If you have used JSX, the mental model is similar here. The kebab-case equivalent `<my-component>` also works in the template - however PascalCase component tags are strongly recommended for consistency. It also helps differentiating from native custom elements.
88+
`MyComponent` 看做被一个变量所引用。如果使用了 JSX,在这里的使用它的心智模型是一样的。其 kebab-case 格式的 `<my-component>` 同样能在模板中使用。不过,我们强烈建议使用 PascalCase 格式作为组件的标签名称,以便于更好的一致性,同时也有助于区分原生的自定义元素。
9089

91-
### Dynamic Components
90+
### 动态组件
9291

93-
Since components are referenced as variables instead of registered under string keys, we should use dynamic `:is` binding when using dynamic components inside `<script setup>`:
92+
由于组件被引用为变量而不是作为字符串键来注册的,在 `<script setup>` 中要使用动态组件的时候,就应该使用动态的 `:is` 来绑定:
9493

9594
```vue
9695
<script setup>
@@ -104,21 +103,21 @@ import Bar from './Bar.vue'
104103
</template>
105104
```
106105

107-
Note how the components can be used as variables in a ternary expression.
106+
请注意组件是如何在三元表达式中被当做变量使用的。
108107

109-
### Recursive Components
108+
### 递归组件
110109

111-
An SFC can implicitly refer to itself via its filename. E.g. a file named `FooBar.vue` can refer to itself as `<FooBar/>` in its template.
110+
一个单文件组件可以通过它的文件名被其自己所引用。例如:名为 `FooBar.vue` 的组件可以在其模板中用 `<FooBar/>` 引用它自己。
112111

113-
Note this has lower priority than imported components. If you have a named import that conflicts with the component's inferred name, you can alias the import:
112+
请注意这种方式相比于 import 导入的组件优先级更低。如果有命名的 import 导入和组件的推断名冲突了,可以使用 import 别名导入:
114113

115114
```js
116115
import { FooBar as FooBarChild } from './components'
117116
```
118117

119-
### Namespaced Components
118+
### 命名空间组件
120119

121-
You can use component tags with dots like `<Foo.Bar>` to refer to components nested under object properties. This is useful when you import multiple components from a single file:
120+
可以使用带点的组件标记,例如 `<Foo.Bar>` 来引用嵌套在对象属性中的组件。这在需要从单个文件中导入多个组件的时候非常有用:
122121

123122
```vue
124123
<script setup>
@@ -132,9 +131,9 @@ import * as Form from './form-components'
132131
</template>
133132
```
134133

135-
## `defineProps` and `defineEmits`
134+
## `defineProps` `defineEmits`
136135

137-
To declare options like `props` and `emits` with full type inference support, we can use the `defineProps` and `defineEmits` APIs, which are automatically available inside `<script setup>`:
136+
为了声明 `props` `emits` 选项且具备完整的类型推断,可以使用 `defineProps` `defineEmits` API,它们在 `<script setup>` 中都是自动可用的:
138137

139138
```vue
140139
<script setup>
@@ -147,21 +146,21 @@ const emit = defineEmits(['change', 'delete'])
147146
</script>
148147
```
149148

150-
- `defineProps` and `defineEmits` are **compiler macros** only usable inside `<script setup>`. They do not need to be imported, and are compiled away when `<script setup>` is processed.
149+
- `defineProps` `defineEmits` 都是只在 `<script setup>` 中才能使用的**编译器宏**。他们不需要导入,且会在处理 `<script setup>` 的时候被编译处理掉。
151150

152-
- `defineProps` accepts the same value as the `props` option, while `defineEmits` accepts the same value as the `emits` option.
151+
- `defineProps` 接收与 `props` 属性相同的值,`defineEmits` 也接收 `emits` 属性相同的值。
153152

154-
- `defineProps` and `defineEmits` provide proper type inference based on the options passed.
153+
- `defineProps` `defineEmits` 在选项传入后,会提供恰当的类型推断。
155154

156-
- The options passed to `defineProps` and `defineEmits` will be hoisted out of setup into module scope. Therefore, the options cannot reference local variables declared in setup scope. Doing so will result in a compile error. However, it _can_ reference imported bindings since they are in the module scope as well.
155+
- 传入到 `defineProps` `defineEmits` 的选项会从 setup 中提升到模块的范围。因此,传入的选项不能引用在 setup 范围中声明的局部变量。这样做会引起编译错误。但是,它*可以*引用导入的绑定,因为它们也在模块范围内。
157156

158-
If you are using TypeScript, it is also possible to [declare props and emits using pure type annotations](#typescript-only-features).
157+
如果使用了 Typescript,[使用纯类型声明来声明 prop 和 emits](#typescript-only-features) 也是可以的。
159158

160159
## `defineExpose`
161160

162-
Components using `<script setup>` are **closed by default** - i.e. the public instance of the component, which is retrieved via template refs or `$parent` chains, will **not** expose any of the bindings declared inside `<script setup>`.
161+
使用 `<script setup>` 的组件是**默认关闭**的,也即通过模板 ref 或者 `$parent` 链获取到的组件的公开实例,不会暴露任何在 `<script setup>` 中声明的绑定。
163162

164-
To explicitly expose properties in a `<script setup>` component, use the `defineExpose` compiler macro:
163+
为了在 `<script setup>` 组件中明确要暴露出去的属性,使用 `defineExpose` 编译器宏:
165164

166165
```vue
167166
<script setup>
@@ -177,11 +176,11 @@ defineExpose({
177176
</script>
178177
```
179178

180-
When a parent gets an instance of this component via template refs, the retrieved instance will be of the shape `{ a: number, b: number }` (refs are automatically unwrapped just like on normal instances).
179+
当父组件通过模板 ref 的方式获取到当前组件的实例,获取到的实例会像这样 `{ a: number, b: number }` (ref 会和在普通实例中一样被自动解包)
181180

182-
## `useSlots` and `useAttrs`
181+
## `useSlots` `useAttrs`
183182

184-
Usage of `slots` and `attrs` inside `<script setup>` should be relatively rare, since you can access them directly as `$slots` and `$attrs` in the template. In the rare case where you do need them, use the `useSlots` and `useAttrs` helpers respectively:
183+
`<script setup>` 使用 `slots``attrs` 的情况应该是很稀少的,因为可以在模板中通过 `$slots` `$attrs` 来访问它们。在那些稀少的需要使用它们的场景中,可以分别用 `useSlots` `useAttrs` 两个辅助函数来使用:
185184

186185
```vue
187186
<script setup>
@@ -192,54 +191,54 @@ const attrs = useAttrs()
192191
</script>
193192
```
194193

195-
`useSlots` and `useAttrs` are actual runtime functions that return the equivalent of `setupContext.slots` and `setupContext.attrs`. They can be used in normal composition API functions as well.
194+
`useSlots` `useAttrs` 是真实的运行时函数,它会返回与 `setupContext.slots` `setupContext.attrs` 等价的值,同样也能在普通的组合式 API 中使用。
196195

197-
## Usage alongside normal `<script>`
196+
## 与普通的 `<script>` 一起使用
198197

199-
`<script setup>` can be used alongside normal `<script>`. A normal `<script>` may be needed in cases where we need to:
198+
`<script setup>` 可以和普通的 `<script>` 一起使用。普通的 `<script>` 在有这些需要的情况下或许会被使用到:
200199

201-
- Declare options that cannot be expressed in `<script setup>`, for example `inheritAttrs` or custom options enabled via plugins.
202-
- Declaring named exports.
203-
- Run side effects or create objects that should only execute once.
200+
- 无法在 `<script setup>` 声明的选项,例如 `inheritAttrs` 或通过插件启用的自定义的选项。
201+
- 声明命名导出。
202+
- 运行副作用或者创建只需要执行一次的对象。
204203

205204
```vue
206205
<script>
207-
// normal <script>, executed in module scope (only once)
206+
// 普通 <script>, 在模块范围下执行(只执行一次)
208207
runSideEffectOnce()
209208
210-
// declare additional options
209+
// 声明额外的选项
211210
export default {
212211
inheritAttrs: false,
213212
customOptions: {}
214213
}
215214
</script>
216215
217216
<script setup>
218-
// executed in setup() scope (for each instance)
217+
// setup() 作用域中执行 (对每个实例皆如此)
219218
</script>
220219
```
221220

222-
## Top-level `await`
221+
## 顶层 `await`
223222

224-
Top-level `await` can be used inside `<script setup>`. The resulting code will be compiled as `async setup()`:
223+
`<script setup>` 中可以使用顶层 `await`。结果代码会被编译成 `async setup()`
225224

226225
```vue
227226
<script setup>
228227
const post = await fetch(`/api/post/1`).then(r => r.json())
229228
</script>
230229
```
231230

232-
In addition, the awaited expression will be automatically compiled in a format that preserves the current component instance context after the `await`.
231+
另外,await 的表达式会自动编译成在 `await` 之后保留当前组件实例上下文的格式
233232

234-
:::warning Note
235-
`async setup()` must be used in combination with `Suspense`, which is currently still an experimental feature. We plan to finalize and document it in a future release - but if you are curious now, you can refer to its [tests](https://github.com/vuejs/vue-next/blob/master/packages/runtime-core/__tests__/components/Suspense.spec.ts) to see how it works.
233+
:::warning 注意
234+
`async setup()` 必须与 `Suspense` 组合使用,`Suspense` 目前还是处于实验阶段的特性。我们打算在将来的某个发布版本中开发完成并提供文档 - 如果你现在感兴趣,可以参照 [tests](https://github.com/vuejs/vue-next/blob/master/packages/runtime-core/__tests__/components/Suspense.spec.ts) 看它是如何工作的。
236235
:::
237236

238-
## TypeScript-only Features
237+
## 仅限 TypeScript 的功能
239238

240-
### Type-only props/emit declarations
239+
### 仅限类型的 props/emit 声明
241240

242-
Props and emits can also be declared using pure-type syntax by passing a literal type argument to `defineProps` or `defineEmits`:
241+
props 和 emits 都可以使用传递字面量类型的纯类型语法做为参数给 `defineProps` `defineEmits` 来声明:
243242

244243
```ts
245244
const props = defineProps<{
@@ -253,26 +252,26 @@ const emit = defineEmits<{
253252
}>()
254253
```
255254

256-
- `defineProps` or `defineEmits` can only use either runtime declaration OR type declaration. Using both at the same time will result in a compile error.
255+
- `defineProps` `defineEmits` 只能是要么使用运行时声明,要么使用类型声明。同时使用两种声明方式会导致编译报错。
257256

258-
- When using type declaration, the equivalent runtime declaration is automatically generated from static analysis to remove the need for double declaration and still ensure correct runtime behavior.
257+
- 使用类型声明的时候,静态分析会自动生成等效的运行时声明,以消除双重声明的需要并仍然确保正确的运行时行为。
259258

260-
- In dev mode, the compiler will try to infer corresponding runtime validation from the types. For example here `foo: String` is inferred from the `foo: string` type. If the type is a reference to an imported type, the inferred result will be `foo: null` (equal to `any` type) since the compiler does not have information of external files.
259+
- 在开发环境下,编译器会试着从类型来推断对应的运行时验证。例如这里从 `foo: string` 类型中推断出 `foo: String`。如果类型是对导入类型的引用,这里的推断结果会是 `foo: null` (`any` 类型相等),因为编译器没有外部文件的信息。
261260

262-
- In prod mode, the compiler will generate the array format declaration to reduce bundle size (the props here will be compiled into `['foo', 'bar']`)
261+
- 在生产模式下,编译器会生成数组格式的声明来减少打包体积 (这里的 props 会被编译成 `['foo', 'bar']`)
263262

264-
- The emitted code is still TypeScript with valid typing, which can be further processed by other tools.
263+
- 生成的代码仍然是有着类型的 Typescript 代码,它会在后续的流程中被其它工具处理。
265264

266-
- As of now, the type declaration argument must be one of the following to ensure correct static analysis:
265+
- 截至目前,类型声明参数必须是以下内容之一,以确保正确的静态分析:
267266

268-
- A type literal
269-
- A reference to an interface or a type literal in the same file
267+
- 类型字面量
268+
- 在同一文件中的接口或类型字面量的引用
270269

271-
Currently complex types and type imports from other files are not supported. It is theoretically possible to support type imports in the future.
270+
现在还不支持复杂的类型和从其它文件进行类型导入。理论上来说,将来是可能实现类型导入的。
272271

273-
### Default props values when using type declaration
272+
### 使用类型声明时的默认 props
274273

275-
One drawback of the type-only `defineProps` declaration is that it doesn't have a way to provide default values for the props. To resolve this problem, a `withDefaults` compiler macro is also provided:
274+
仅限类型的 `defineProps` 声明的不足之处在于,它没有可以给 props 提供默认值的方式。为了解决这个问题,提供了 `withDefaults` 编译器宏:
276275

277276
```ts
278277
interface Props {
@@ -286,8 +285,8 @@ const props = withDefaults(defineProps<Props>(), {
286285
})
287286
```
288287

289-
This will be compiled to equivalent runtime props `default` options. In addition, the `withDefaults` helper provides type checks for the default values, and ensures the returned `props` type has the optional flags removed for properties that do have default values declared.
288+
上面代码会被编译为等价的运行时 props `default` 选项。此外,`withDefaults` 辅助函数提供了对默认值的类型检查,并确保返回的 `props` 的类型删除了已声明默认值的属性的可选标志。
290289

291-
## Restriction: No Src Imports
290+
## 限制:没有 Src 导入
292291

293-
Due to the difference in module execution semantics, code inside `<script setup>` relies on the context of an SFC. When moved into external `.js` or `.ts` files, it may lead to confusion for both developers and tools. Therefore, **`<script setup>`** cannot be used with the `src` attribute.
292+
由于模块执行语义的差异,`<script setup>` 中的代码依赖单文件组件的上下文。当将其移动到外部的 `.js` 或者 `.ts` 文件中的时候,对于开发者和工具来说都会感到混乱。因而 **`<script setup>`** 不能和 `src` attribute 一起使用。

0 commit comments

Comments
 (0)