1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VueでDOM更新後の要素取得(nextTick)

Last updated at Posted at 2022-03-15

Vueでの機能でnextTickについてのメモ

Watchしてるdataの変数の変更を検知したとしても、それと連動しているDomの変更を検知することは難しいが、nextTickを使えば簡単に検知、またイベントハンドリングすることが容易である。

<button v-on:click="list.push(`list${list.length+1}`)">addList</button>
<ul ref="target">
    <li v-for="str in list">{{ str }}</li>
</ul>
new Component({
    el: '#app',
    data: {
        list: [
            'list1',
            'list2',
            'list3',
            'list4',
        ]
    },
    watch: {
        list: () => {
            this.$nextTick(() => {
                console.log(`ulの縦幅:${this.$refs.list.offsetHeight}`);
            })
        }
    }
})

addListのボタンクリック時にはかれるconsoleは、<li>タグ5つ分の縦幅が出力されるだろう。

だがもし仮に、以下のように実装していたら...

new Component({
    el: '#app',
    data: {
        list: [
            'list1',
            'list2',
            'list3',
            'list4',
        ]
    },
    watch: {
        list: () => {
            console.log(`ulの縦幅:${this.$refs.list.offsetHeight}`);
        }
    }
})

listの変数には'list'が追加されているが、このときDOMの変更はまだ行われていないため、
consoleは<li>タグ4つ分の縦幅が出力されるだろう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?