簡體   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