ArraySearch.vue 2.11 KB
Newer Older
1
<script>
2 3
import Searchable from '../js/searchable.js'
import getData from '../js/get-data.js'
4 5 6 7 8 9 10 11

export default {
  props: {
    array: {
      type: Array,
      required: true,
    },
    options: {
12
      type: [Object, Function],
13
    },
14
    onConstruct: {
15
      type: Function,
16
    },
17
    inputEventIsNative: {
18
      type: Boolean,
19
      default: true,
20
    },
21
    parentData: { type: Object }
22 23 24
  },
  data () {
    return {
25
      instance: {},
26 27 28
    }
  },
  methods: {
29 30
    getData: getData,

31
    handleInput (evt) {
32
      const payload = this.inputEventIsNative ? evt.target.value : payload = evt // Capture payload emitted from child components
33
      this.instance.setQuery(payload)
34 35 36
    },
    construct () {
      const options = this.getData(this.options, this.api),
37
            instance = new Searchable(this.array, options)
38

39
      if (this.onConstruct !== undefined) this.onConstruct(instance, this.api)
40

41
      return instance
42 43
    },

44 45
    // Third party
    search () {
46
      this.instance.search(...arguments)
47
    },
48 49
    setQuery () {
      this.instance.setQuery(...arguments)
50
    }
51
  },
52
  watch: {
53 54 55
    array () {
      this.instance = this.construct()
    },
56
    options () {
57
      this.instance = this.construct()
58 59 60 61 62 63 64 65
    }
  },
  created () {
    this.api = {
      emit: (event, payload) => this.$emit(event, payload),
      handleInput: this.handleInput
    }

66
    this.instance = this.construct()
67 68 69 70
  },
  mounted () {
    this.api.el = this.$el
  },
71 72 73 74 75 76 77 78 79 80 81 82
  computed: {
    provisions () {
      return {
        handleInput: this.handleInput,

        query: this.instance.query,
        results: this.instance.results,
        search: this.search,
        setQuery: this.setQuery,

        el: () => this.$el,
        emit: (event, payload) => this.$emit(event, payload),
83
        parentData: this.parentData
84 85 86
      }
    }
  },
87
  provide() {
88
    return { arraySearch: this.provisions }
89
  },
90
  render () {
91
    if (this.$scopedSlots.default !== undefined) {
92
      return this.$scopedSlots.default(this.provisions)
93 94 95 96 97
    } else if (this.$slots.default !== undefined) {
      return this.$slots.default[0]
    } else {
      return null
    }
98 99 100
  },
}
</script>