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

update key-attribute.md #717

Merged
merged 1 commit into from
Sep 10, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions src/guide/migration/key-attribute.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ badges:
## 概览

- **新增**:对于 `v-if`/`v-else`/`v-else-if` 的各分支项 `key` 将不再是必须的,因为现在 Vue 会自动生成唯一的 `key`。
- **非兼容**:如果你手动提供 `key`,那么每个分支必须使用唯一的 `key`。你不能通过故意使用相同的 `key` 来强制重用分支。
- **非兼容**:如果你手动提供 `key`,那么每个分支必须使用唯一的 `key`。你将不再能通过故意使用相同的 `key` 来强制重用分支。
- **非兼容**:`<template v-for>` 的 `key` 应该设置在 `<template>` 标签上 (而不是设置在它的子节点上)。

## 背景

特殊的 `key` attribute 被用于提示 Vue 的虚拟 DOM 算法来保持对节点身份的持续跟踪。这样 Vue 可以知道何时能够重用和修补现有节点,以及何时需要对它们重新排序或重新创建。关于其它更多信息,可以查看以下章节:
特殊的 `key` attribute 被作为 Vue 的虚拟 DOM 算法的提示,以保持对节点身份的持续跟踪。这样 Vue 就可以知道何时能够重用和修补现有节点,以及何时需要对它们重新排序或重新创建。关于其它更多信息,可以查看以下章节:

- [列表渲染:维护状态](/guide/list.html#%E7%BB%B4%E6%8A%A4%E7%8A%B6%E6%80%81)
- [API 参考:特殊指令 `key`](/api/special-attributes.html#key)
- [API 参考:特殊的 `key` attribute](/api/special-attributes.html#key)

## 在条件分支中

Vue 2.x 建议在 `v-if`/`v-else`/`v-else-if` 的分支中使用 `key`。
Vue 2.x 中,建议在 `v-if`/`v-else`/`v-else-if` 的分支中使用 `key`。

```html
<!-- Vue 2.x -->
Expand All @@ -43,18 +43,18 @@ Vue 2.x 建议在 `v-if`/`v-else`/`v-else-if` 的分支中使用 `key`。
<div v-if="condition" key="a">Yes</div>
<div v-else key="a">No</div>

<!-- Vue 3.x (recommended solution: remove keys) -->
<!-- Vue 3.x (推荐方案:移除 key) -->
<div v-if="condition">Yes</div>
<div v-else>No</div>

<!-- Vue 3.x (alternate solution: make sure the keys are always unique) -->
<!-- Vue 3.x (替代方案:确保 key 始终是唯一的) -->
<div v-if="condition" key="a">Yes</div>
<div v-else key="b">No</div>
```

## 结合 `<template v-for>`

在 Vue 2.x 中 `<template>` 标签不能拥有 `key`。不过你可以为其每个子节点分别设置 `key`。
在 Vue 2.x 中`<template>` 标签不能拥有 `key`。不过,你可以为其每个子节点分别设置 `key`。

```html
<!-- Vue 2.x -->
Expand All @@ -64,7 +64,7 @@ Vue 2.x 建议在 `v-if`/`v-else`/`v-else-if` 的分支中使用 `key`。
</template>
```

在 Vue 3.x 中 `key` 则应该被设置在 `<template>` 标签上。
在 Vue 3.x 中`key` 则应该被设置在 `<template>` 标签上。

```html
<!-- Vue 3.x -->
Expand All @@ -74,7 +74,7 @@ Vue 2.x 建议在 `v-if`/`v-else`/`v-else-if` 的分支中使用 `key`。
</template>
```

类似地,当使用 `<template v-for>` 时存在使用 `v-if` 的子节点,`key` 应改为设置在 `<template>` 标签上。
类似地,当使用 `<template v-for>` 时如果存在使用 `v-if` 的子节点,`key` 应改为设置在 `<template>` 标签上。

```html
<!-- Vue 2.x -->
Expand Down