'window'未在Vue.js 2中定义

Jor*_*rdy 10 javascript window undefined vue.js vuejs2

我目前正在将我的应用程序从Vue.js 1升级到Vue.js 2.我的主要组件中的以下函数存在问题:

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

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

我的控制台显示此错误:'window' is not defined 这怎么可能?我不明白原因.如何解决这个问题以及新版本出现这个问题的原因是什么?

---编辑---一些额外的代码:

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');
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

主要成分:

<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>
Run Code Online (Sandbox Code Playgroud)

Hex*_*dus 7

使用浏览器引用最安全的地方是mounted()生命周期钩子.特别是如果您正在使用像Nuxt.js或类似的SSR设置.

  • 使用的是Nuxt,它在`created()`中不起作用,但在`mount()`中起作用。 (2认同)

dar*_*ten 5

尝试将侦听器放入您的created()方法中

您还会丢失上下文,this因此请使用词汇粗箭头来保留上下文

// 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
Run Code Online (Sandbox Code Playgroud)

完全未经测试,但应该可以工作(vue 2.x)


Jor*_*rdy 5

它与Eslint有关。把这个:

"env": {
    "browser": true,
    "node": true
}
Run Code Online (Sandbox Code Playgroud)

.eslintrc.js在我的根里面修复了这个问题。(来源