Skip to content

Migration Guide > v-for Array Refs の翻訳 #140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions src/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ const sidebar = {
collapsable: true,
children: [
'migration/introduction',
'migration/array-refs',
'migration/async-components',
'migration/attribute-coercion',
'migration/custom-directives',
Expand Down
69 changes: 69 additions & 0 deletions src/guide/migration/array-refs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
title: v-forのref配列
badges:
- breaking
---

# {{ $frontmatter.title }} <MigrationBadges :badges="$frontmatter.badges" />

Vue 2 では、`v-for` の中で `ref` 属性を記述すると、対応する `$refs` プロパティに参照の配列を入れます。この動作は、入れ子になった `v-for` がある場合、曖昧で非効率的になります。

Vue 3 では、この記述では `$refs` に配列が作成されなくなりました。1つのバインディングから複数の参照を取得するには、関数に `ref` をバインドします (これは新機能です)。

```html
<div v-for="item in list" :ref="setItemRef"></div>
```

オプション API を使う場合

```js
export default {
data() {
return {
itemRefs: []
}
},
methods: {
setItemRef(el) {
this.itemRefs.push(el)
}
},
beforeUpdate() {
this.itemRefs = []
},
updated() {
console.log(this.itemRefs)
}
}
```

コンポジション API を使う場合

```js
import { ref, onBeforeUpdate, onUpdated } from 'vue'

export default {
setup() {
let itemRefs = []
const setItemRef = el => {
itemRefs.push(el)
}
onBeforeUpdate(() => {
itemRefs = []
})
onUpdated(() => {
console.log(itemRefs)
})
return {
itemRefs,
setItemRef
}
}
}
```

注意点

- `itemRefs` は配列である必要はありません。 反復キーで参照できるオブジェクトでも構いません。

- これにより、必要に応じて `itemRefs` をリアクティブにして監視することもできます。