0

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?

Brian
  • 1
  • 1

1 Answers1

0

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...

Brian
  • 1
  • 1
  • When questions end up being the result of a typo or a non-reproducible problem like this one it's generally best to just close them, as they're unlikely to be useful to future users. (This may also happen automatically if enough people vote that way.) If it's an issue that someone else might conceivably run into as well, though, go ahead and leave the question open even if it's a very simple fix. Self-answering a question is fine, but it should be a real answer (therefore this one should probably be deleted). – Daniel Beck Aug 09 '18 at 20:36
  • (Don't worry about it too much, though; SO is complicated, you're doing better than many new users :) – Daniel Beck Aug 09 '18 at 20:36
  • 1
    what a kind guy! thank you my friend. you make me feel like wanna make more productive questions! i'm gonna have to learn about stackoverflow's user interface more! thank you so much! have a nice day :) – Brian Aug 09 '18 at 21:50