LoginSignup
155
107

More than 5 years have passed since last update.

VueコンポーネントでWindowサイズ変更検知&値取得

Last updated at Posted at 2018-05-02

実装方法

ブラウザのリサイズはwindowのイベントでVueが直接関与する部分ではないため、コンポーネントの作成時にイベントリスナを追加します。コンポーネント削除時には、忘れずにイベントリスナも削除します。

サンプルコード

<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 () {
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

動作がモッサリするようならlodashの_.debounce等を使用し、発火頻度を落とすと良いみたい。

155
107
4

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
155
107