18

I'm currently upgrading my application from Vue.js 1 to Vue.js 2. I have a problem with the following function in my main component:

<script>
  export default {
    ready: function listenKeyUp() {
      window.addEventListener('keyup', this.handleKeyUp());
    },

    methods: {
      handleKeyUp(e) {
        if (e.keyCode === 27) {
          this.$router.go({ name: '/' });
        }
      },
    },
  };
</script>

My console shows this error: 'window' is not defined How is this possible? I don't understand the reason. How to fix this and why is this problem coming up with the new version?

--- EDIT --- Some additional code:

main.js:

// Import plugins
import Vue from 'vue';
import VueResource from 'vue-resource';
import VueI18n from 'vue-i18n';

// Import mixins
import api from './mixins/api';

// Import router config
import router from './router';


// Register plugins
Vue.use(VueResource);
Vue.use(VueI18n);
Vue.mixin(api);


// Go
new Vue({
  router,
}).$mount('#app');

index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>New website</title>

        <link rel="shortcut icon" href="/static/favicon.ico" />
        <link rel="apple-touch-icon" href="/static/mobile.png">

        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato"> 
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    </head>
    <body>
        <div id="app">
            <router-view></router-view>
        </div>

        <noscript>
            <div class="container">
                <div class="col-sm-6 col-sm-offset-3">
                    <div class="alert alert-danger">
                        JavaScript is disabled in your web browser!
                    </div>
                </div>
            </div>
        </noscript>

    </body>
</html>

Main component:

<template>
    <div>

        <div class="container">
            <header>
                HEADER HERE
            </header>
        </div>


        <div id="modal" v-if=" $route.name !== 'home' " transition="modal">
            <div id="modal-bg" :to="{ name: 'home' }"></div>
            <div id="modal-container">
                <div id="modal-header">
                    <h2>Modal</h2>
                    <router-link id="modal-close" :to="{ name: 'home' }">X</router-link>
                </div>
                <router-view></router-view>
            </div>
        </div>


        <nav id="primary-navigation">
            <div class="container-fluid">
                <div class="row">
                    NAV HERE
                </div>
            </div>
        </nav>

    </div>
</template>


<script>
  /* SCRIPT PART, SEE TOP OF THIS POST */
</script>


<style lang="scss">
  /* CSS */
</style>

4 Answers 4

24

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Was using Nuxt, and it wasn't working in created(), but worked in mounted().
6

It's related to Eslint. Putting this:

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

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

Comments

5

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 export
created() {
  // 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)

4 Comments

Thank you. Tried your code but unfortunately the NPM console still displays: 'window' is not defined. How is that possible? What could be the problem?
The npm console? Isn't this running in the browser?
No, after typing 'npm run dev' in the console.
Found out it was being related to eslint, see my answer. Thanks for your help anyway!
0

Fix for vue-cli 3.x projects by editing (creating) vue.config.js:

module.exports = {
    configureWebpack: config => {
        config.output.globalObject = "this"
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.