繁体   English   中英

仅当在vue.js监视对象中的此方法中使用闭包时才能正常工作的原因

[英]reason for working properly only when using closure in this method in vue.js watch object

的index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>VueJS</title>
    <script src="vue.js"></script>
  </head>
  <body>
    <div id="app">
      <button @click="counter++">increase</button>
      <button @click="counter--">decrease</button>
      <p>Counter: {{counter}}</p>
      <p>Result: {{ result() }} | {{ output }}</p>
    </div>
  </body>
</html>

<script src="app.js"></script>


app.js

new Vue({
  el: "#app",
  data: {
  counter: 0
  },
  computed: {
    output() {
      console.log('Computed!')
      return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5'
    }
  },
  watch: {
    counter(value) {
      var vm = this;
      setTimeout(() => {
        vm.counter = 0;
      }, 2000)
    }
  },
  methods: {
    result() {
      console.log('Method!')
      return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5'
    }
  }
})

嗨,这是我的代码。

更改计数器值后,手表属性就会知道这一点,并在2秒后将计数器更改为0。

此代码没有问题! 但是我在手表属性上有一件不了解的事情。 为什么watch属性中的counter方法仅在使用闭包功能时才起作用?

counter(value) {
  var vm = this;
  setTimeout(() => {
    vm.counter = 0;
  }, 2000)
}

这个工作!

counter(value) {
  setTimeout(() => {
    this.counter = 0;
  }, 2000)
}

但这不起作用! (即使2秒后计数器也不会变为零)

为什么会发生?

解决了 我的错。 谢谢丹尼尔! 其实我是新来的,我不知道以这样的问题结束是否正确……

暂无
暂无

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

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