154
108

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 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等を使用し、発火頻度を落とすと良いみたい。

154
108
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
154
108

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?