简体   繁体   中英

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'
    }
  }
})

hi, here is my code.

once counter value is changed, watch property knows this and after 2 sec, change counter into 0.

this code has no problem! but i got one thing that don't understand on watch property. why does counter method in watch property work only when using closure feature?

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

this do work!

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

but this doesn't work! (counter doesn't become zero even after 2 sec)

why does it happen?

it's resolved. my mistake. thank you Daniel! actually i'm new here, i don't know exactly whether it's right to end up with this question like this...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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