LoginSignup
0
0

More than 1 year has passed since last update.

watcherを使ってx秒後にカウンターをゼロにする

Posted at

watchは非同期処理によく使う
*ちなみにreturnは非同期処理では使えない。
*thisも非同期処理では使えない.vmを設定してvmを使って指定します。
*vm(ViewModelの略)をVueインスタンスの変数名としてよく使います。

setTimeoutは、 指定された処理を指定された時間後に1回実行します。
第一引数にはコード文字列か関数オブジェクトを指定します。第二引数には処理待ち時間もしくは実行間隔をmsecで指定します。

<body>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
  <div id="app">
    <p>{{ counter }}</p>
    <button @click="counter += 1">+1</button>
    <p>{{ lessThanThree }}</p>

</div>
<script>
  new Vue({
    el: '#app',
    data: {
     counter: 0
    },
    computed: {
      lessThanThree: function() {
        console.log('Computed');
        return this.counter > 3 ? '3以上' : '3以下'
        }
      },
      watch: {
        counter: function() {
          var vm = this;
          setTimeout(function() {
          vm.counter = 0
          }, 3000)
        }
      }
  })
</script>
</body>

3秒経ったらカウンターはゼロに戻りました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0