'window' is not defined in Vue.js 2 'window' is not defined in Vue.js 2 vue.js vue.js

'window' is not defined in Vue.js 2


The safest place to use browser references is the mounted() lifecycle hook. Especially if you're using a SSR setup like Nuxt.js or similar.


It's related to Eslint. Putting this:

"env": {    "browser": true,    "node": true}

inside .eslintrc.js in my root fixed the issue. (source)


Try putting the listener in your created() method

You're also going to be losing context on your this so use a lexical fat arrow to preserve the context

// rest of exportcreated() {  // make an event listener and pass the right `this` through  window.addEventListener('keyup', (event) => {    // if the key is escape    if (event.keyCode === 27) {      // due to `=>` this is the this you're expecting      this.keyHandler()    }  }},methods: {  keyHandler() {    // this *should* be the right this    this.$router.go({ name: '/' })  }}// rest of export

Completely untested but it should work (vue 2.x)