简体   繁体   English

对 VueJS 生命周期钩子的误解

[英]Misunderstanding lifecycle hooks VueJS

I'm starting a tuto on the framework Vue.JS.我正在开始学习框架 Vue.JS。

I m using the life cycle created of the Vue.我正在使用 Vue创建的生命周期。 I thought that this function was called once the vue is created.我认为一旦创建了 vue,就会调用这个函数。 But in this example, A behavior that I do not understand.但在这个例子中,我不理解的行为。

<template>
  <div class="game">
    <span class="round"  v-on:click="clickOnRound" v-on:click.alt="bonus"></span>
  </div>
</template>

<script>
  export default {
    name: 'game',
    created: function () {
      console.log('On Vue created')
      document.onkeydown = this.start
    },
    methods: {
      clickOnRound: function (event) {
        console.log('Click')
      },
      bonus: function (event) {
        console.log('Click + alt')
        console.log(event)
      },
      start: function (event) {
        console.log('Start called')
        console.log(event)
      }
    }
  }
</script>

When I type a letter on the keyboard, the function start is called, without calling the function of created.当我在键盘上键入一个字母时,函数 start 被调用,而不调用 created 函数。

Here the console output:这里是控制台输出:

  • On Vue created在 Vue 创建
  • Start called开始调用
  • Start called开始调用
  • Start called开始调用
  • Start called开始调用

I can t understand how the start function is called without calling each time the created function , because the start function is inside the created function.如果不每次调用 created 函数,我无法理解如何调用 start 函数,因为 start 函数在 created 函数内部。

 created: function () {
      console.log('On Vue created')
      document.onkeydown = this.start
    },

The code inside created block will be only called once when the vue instance is created, thats why you are seeing log : On Vue created only once.创建块中的代码只会在创建 vue 实例时调用一次,这就是为什么您会看到日志: On Vue created一次。

Why are you see Start called on each key pressed: because you have registered this.start on document.onkeydown , so on each key press, this.start will get executed.为什么每次按下按键时都会Start called :因为您已经在document.onkeydown上注册this.start ,所以在每次按键时, this.start都会被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM