3
1

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 3 years have passed since last update.

Vue でウィンドウサイズの変更を検知したいとき

Posted at

Vue を使っていてウィンドウのリサイズを検知するには、Vuetify というコンポーネントフレームワークの v-resize というカスタムディレクティブが便利です。

<template>
  <span v-resize="onResize">{{ windowSize }}</span>
</template>

<script>
  export default {
    data: () => ({
      windowSize: {
        x: 0,
        y: 0,
      },
    }),

    mounted () {
      this.onResize()
    },

    methods: {
      onResize () {
        this.windowSize = { x: window.innerWidth, y: window.innerHeight }
      },
    },
  }
</script>

このように、テンプレートで v-resize に発火したいメソッド名を渡すだけで、ウィンドウのサイズが変更された時にそのメソッドを実行することができます。

ウィンドウや要素の幅に応じて動的に何かを設定する必要があるコードでは便利ですね。手元のコード量がほとんど増えないのが個人的にうれしいポイントです。

3
1
0

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?