LoginSignup
1

More than 3 years have passed since last update.

Vue.jsのkeyupやkeydownで数秒後に発火する処理を実装したい

Last updated at Posted at 2019-11-14

結論

@keyupで呼び出す関数をlodashdebounceでnミリ秒後指定する。

Vue.jsでkeyupイベントで発火

さて、keyupやkeydownで発火させるのはかんたんだ…。
でも入力中に毎回発火させるのは嫌だな〜

<template>
  <div>
    <input @keyup="doAlert">
  <div>
</template>

<script>
export default {
  name: 'hogeComponent',
  methods: {
    doAlert() {
      alert('アラートじゃ!');
    }
  }
}
</script>

数秒後に発火させたい & 時間内にもう一度イベント発火が起こればカウントリセット

lodashのdebounceに頼る

lodashをインストール(npmでもOK)

yarn add lodash
  1. lodashをimportする
  2. doAlertメソッドを_.debounce()で指定ミリ秒後呼び出しにする
<template>
  <div>
    <input @keyup="doAlert">
  <div>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'hogeComponent',
  methods: {
    doAlert: _.debounce(function() {
      alert('アラートじゃ!');
    }, 500) // 500ms指定
  }
}
</script>

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
1