Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
97
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@techneconn

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

実装方法

ブラウザのリサイズは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等を使用し、発火頻度を落とすと良いみたい。

97
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
97
Help us understand the problem. What is going on with this article?