diff --git a/src/.vuepress/config.js b/src/.vuepress/config.js index aff8c464..b3d7bd77 100644 --- a/src/.vuepress/config.js +++ b/src/.vuepress/config.js @@ -111,6 +111,7 @@ const sidebar = { collapsable: true, children: [ 'migration/introduction', + 'migration/array-refs', 'migration/async-components', 'migration/attribute-coercion', 'migration/custom-directives', diff --git a/src/guide/migration/array-refs.md b/src/guide/migration/array-refs.md new file mode 100644 index 00000000..c97fa7d0 --- /dev/null +++ b/src/guide/migration/array-refs.md @@ -0,0 +1,69 @@ +--- +title: v-forのref配列 +badges: +- breaking +--- + +# {{ $frontmatter.title }} + +Vue 2 では、`v-for` の中で `ref` 属性を記述すると、対応する `$refs` プロパティに参照の配列を入れます。この動作は、入れ子になった `v-for` がある場合、曖昧で非効率的になります。 + +Vue 3 では、この記述では `$refs` に配列が作成されなくなりました。1つのバインディングから複数の参照を取得するには、関数に `ref` をバインドします (これは新機能です)。 + +```html +
+``` + +オプション 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` をリアクティブにして監視することもできます。 \ No newline at end of file