LoginSignup
19
6

More than 3 years have passed since last update.

Nuxt.jsで`window is not defined` または `document is not defined`になったときの対処法

Posted at

公式ドキュメントにある通りにやれば問題ないんですが、どうやればいいのかいまいち具体的にピンとこなかったので書き残しておきます。
(particles.jsを使うのにめっちゃ手間取った。)

if (process.client) {
  require('external_library')
}

window または document が undefined - NuxtJS

VueのSFCにおいて、具体的にはこんな感じ。

importしたライブラリでエラーとなった場合

import 'external_library'として読み込むのではなく、こうする。

<template>
  <div>hoge</div>
</template>

<script>
// requireで読み込む
if (process.browser) {
  require('external_library')
}
export default {
  // hoge
}
</script>

メソッドなどでwindowを呼び出そうとした場合

mountedで使う場合は意識しなくても使えるはず。

<template>
  <div>hoge</div>
</template>

<script>
// こうとか
if (process.browser) {
  // ここに window とか document を使った処理
}

export default {
  // 作成時に使いたかったらこうとか
  created() {
    if (process.browser){
      // ここに window とか document を使った処理
    }
  },
  // DOM生成し終わってから使いたかったらこう
  mounted() {
    // ここに window とか document を使った処理
  }
}
</script>
19
6
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
19
6