aboutsummaryrefslogtreecommitdiff
path: root/src/components/user_autosuggest/user_autosuggest.js
blob: 12a6964a023e09dc0442cb9d2969953746d8cf42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import BlockCard from '../block_card/block_card.vue'

const debounceMilliseconds = 500

export default {
  props: {
    query: {    // function to query results and return a promise
      type: Function,
      required: true
    },
    filter: {   // function to filter results in real time
      type: Function
    },
    placeholder: {
      type: String,
      default: 'Search...'
    }
  },
  components: {
    BlockCard
  },
  data () {
    return {
      term: '',
      timeout: null,
      results: [],
      resultsVisible: false
    }
  },
  computed: {
    filtered () {
      return this.filter ? this.filter(this.results) : this.results
    }
  },
  watch: {
    term (val) {
      this.fetchResults(val)
    }
  },
  methods: {
    fetchResults (term) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.results = []
        if (term) {
          this.query(term).then((results) => { this.results = results })
        }
      }, debounceMilliseconds)
    },
    onInputClick () {
      this.resultsVisible = true
    },
    onClickOutside () {
      this.resultsVisible = false
    }
  }
}