LoginSignup
1
3

More than 3 years have passed since last update.

Vue.jsでコンポーネント更新後に要素をスクロール(TypeScript)

Last updated at Posted at 2020-02-23

結論

・nextTickで更新を待ってから位置を取得する

失敗するコード

この書き方だと、コンポーネントの切り替えが間に合わず、取得位置が切り替え前の位置になる場合があり、思った位置にスクロールしてくれない

// 表示中のコンポーネントの切り替えなど
this.switchComponent(); 

// 上端を基準とする位置を取得
const selectedElement: Element = document.getElementsByClassName('className')[0];
const elementPosition: number = selectedElement.getBoundingClientRect().top;
const currentPosition: number = window.pageYOffset;
const targetPosition: number = elementPosition + currentPosition;

// スクロール
window.scrollTo({
    top: targetPosition,
    behavior: 'smooth',
});

成功するコード

this.$nextTickでコンポーネントの更新を待つことで、切り替え後の位置を正確に取得出来、思った通りの位置にスクロールされる

// 表示中のコンポーネントの切り替えなど
this.switchComponent(); 

this.$nextTick(() => {
    // 上端を基準とする位置を取得
    const selectedElement: Element = document.getElementsByClassName('className')[0];
    const elementPosition: number = selectedElement.getBoundingClientRect().top;
    const currentPosition: number = window.pageYOffset;
    onst targetPosition: number = elementPosition + currentPosition;

    // スクロール
    window.scrollTo({
        top: targetPosition,
        behavior: 'smooth',
    });
});

もうちょいすっきり

// 表示中のコンポーネントの切り替えなど
this.switchComponent(); 

// this.$nexTickがPromiseを返すので
await this.$nextTick(();

// 上端を基準とする位置を取得
const selectedElement: Element = document.getElementsByClassName('className')[0];
const elementPosition: number = selectedElement.getBoundingClientRect().top;
const currentPosition: number = window.pageYOffset;
const targetPosition: number = elementPosition + currentPosition;

// スクロール
window.scrollTo({
    top: targetPosition,
    behavior: 'smooth',
});

1
3
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
3