Sfoglia il codice sorgente

[ADD] fuzzy search in customers grid

Gogs 7 anni fa
parent
commit
0deadb030f
2 ha cambiato i file con 59 aggiunte e 2 eliminazioni
  1. 51 1
      src/components/CustomerSearcher.vue
  2. 8 1
      src/store/modules/customers.js

+ 51 - 1
src/components/CustomerSearcher.vue

@@ -1,11 +1,61 @@
 <template lang="pug">
     .customer-searcher
-        input(type="text" placeholder="Buscar un cliente")
+        input(type="text" placeholder="Buscar un cliente" v-model="search")
 </template>
 
 <script>
+    import Fuse from 'fuse.js'
+    import { mapGetters, mapActions } from 'vuex'
+
     export default {
+        computed: mapGetters({
+            customers: 'getCustomers'
+        }),
+        methods: {
+            initFuse() {
+                if (this.fuse) {
+                    this.fuse.setCollection(this.customers)
+                    return
+                }
 
+                this.fuse = new Fuse(this.customers, {
+                    shouldSort: true,
+                    threshold: 0.4,
+                    location: 0,
+                    distance: 100,
+                    maxPatternLength: 32,
+                    minMatchCharLength: 1,
+                    keys: [
+                        'name',
+                        'display_name'
+                    ]
+                })
+            },
+            fuzzySearch() {
+                this.results = this.fuse.search(this.search)
+            },
+            ...mapActions([
+                'filterCustomers'
+            ])
+        },
+        watch: {
+            customers() {
+                this.initFuse()
+            },
+            search() {
+                this.fuzzySearch()
+            },
+            results() {
+                this.filterCustomers(this.results)
+            }
+        },
+        data() {
+            return {
+                search: '',
+                fuse: null,
+                results: []
+            }
+        }
     }
 </script>
 

+ 8 - 1
src/store/modules/customers.js

@@ -1,11 +1,12 @@
 const state = {
     customers: [],
+    filtered: [],
     selectedCustomer: null
 }
 
 const getters = {
     getCustomers(state) {
-        return state.customers
+        return state.filtered.length === 0 ? state.customers : state.filtered
     },
     hasSelectedCustomer(state) {
         return !!state.selectedCustomer
@@ -18,6 +19,9 @@ const mutations = {
     },
     selectCustomer(state, payload) {
         state.selectedCustomer = payload.customer
+    },
+    applyCustomersFilter(state, payload) {
+        state.filtered = payload
     }
 }
 
@@ -43,6 +47,9 @@ const actions = {
     },
     selectCustomer({ commit }, payload) {
         commit('selectCustomer', payload)
+    },
+    filterCustomers({ commit }, payload) {
+        commit('applyCustomersFilter', payload)
     }
 }