8
9

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-11-07

画面のサイズを取りたい

vueでwindowを使って画面のサイズを取りたい時にハマってしまった

<script>
export default {
  computed: {
    windowSize: () => {
      return { x: window.innerWidth, y: window.innerHeight }
    }
  }
}
</script>

window is not defined

原因

コンポーネントのライフサイクルが関係しており、適切な場所でwindowを使わなければならない

ライフサイクル

解決策

mountedでwindowSizeをセットするように実行


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

    mounted () {
      this.onResize()
    },

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

問題なくwindowを使うことができた!

8
9
1

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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?