1
0
Fork 0

Query system

This commit is contained in:
Joe Wroten 2017-05-08 09:25:37 -04:00
parent 25e6af91c8
commit bb646d64c0
2 changed files with 58 additions and 3 deletions

View file

@ -3,11 +3,17 @@
<div slot="header" class="toolbar"> <div slot="header" class="toolbar">
<q-toolbar-title :padding="0"> <q-toolbar-title :padding="0">
My Spells v2.0 My Spells v2.0
<q-search
v-model="search"
></q-search>
</q-toolbar-title> </q-toolbar-title>
</div> </div>
<div class="layout-view"> <div class="layout-view">
<spell-list :spells="state.spells.data"></spell-list> <spell-list
:spells="spells"
></spell-list>
</div> </div>
</q-layout> </q-layout>
</template> </template>
@ -15,16 +21,32 @@
<script> <script>
import { Loading, Dialog } from 'quasar' import { Loading, Dialog } from 'quasar'
import Vue from 'vue' import Vue from 'vue'
import 'whatwg-fetch'
import Query from '../query'
import { state, dispatch } from '../store' import { state, dispatch } from '../store'
import SpellList from './Spelllist' import SpellList from './Spelllist'
import 'whatwg-fetch'
Vue.component('spell-list', SpellList) Vue.component('spell-list', SpellList)
export default { export default {
computed: {
spells () {
if (this.state.spells.data.length === 0) {
return []
}
let sortBy = this.search.length >= 3 ? 'sortScore' : 'name'
return new Query(this.state.spells.data)
.search('name', this.search, 5)
.sort(sortBy)
.results
}
},
data () { data () {
return { return {
state state,
search: ''
} }
}, },
mounted () { mounted () {

33
src/query.js Normal file
View file

@ -0,0 +1,33 @@
export default class Query {
constructor (data) {
this.data = data.map(item => {
item.sortScore = 0
return item
})
}
get results () {
return this.data
}
search (key, term = '', score = 0) {
if (term.length >= 3) {
this.data = this.data.filter(item => {
let regFind = new RegExp(term, 'gi')
let termMatches = (item[key].match(regFind) || []).length
item.sortScore += termMatches
return termMatches
})
}
return this
}
sort (key = 'sortScore') {
this.data = this.data.sort((a, b) => {
if (a[key] < b[key]) return -1
if (a[key] > b[key]) return 1
return 0
})
return this
}
}