結論
・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',
});