Vue.jsでウィンドウ及びボックスのサイズ取得を行う

Vue.jsでウィンドウ及びボックスのサイズ取得を行う

ベースとなる処理は、VueコンポーネントでWindowサイズ変更検知&値取得を参照した。

<template>
<div>
  <p>window width: {{ width }}</p>
  <p>window height: {{ height }}</p>
</div>
</template>

<script>
export default {
  data: function () {
    return {
      width: window.innerWidth,
      height: window.innerHeight
    }
  },
  methods: {
    handleResize: function() {
      // resizeのたびにこの部分が発火するので、ここでやりたいことをやる
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  mounted: function () {
    this.handleResize(); //ページ表示時に実行させる
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

上記を踏まえてボックス要素の高さと幅を取得する場合、サイズ取得部分を下記のようにする。

this.width = document.querySelector('#hoge').clientWidth;
this.height = document.querySelector('#hoge').clientHeight;

参考サイト

Qiita
VueコンポーネントでWindowサイズ変更検知&値取得
https://qiita.com/yuukive/items/ede7c087843d2f7ef979