-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsyncQuery.js
64 lines (60 loc) · 1.75 KB
/
syncQuery.js
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
58
59
60
61
62
63
64
import updateQuery from 'vue-update-query-mixin'
import typeOf from '../utils/typeof'
import mergeDesc from '../utils/mergeDesc'
const err = msg => { throw new Error('[SyncQuery] ' + msg) }
export default {
mixins: [updateQuery],
methods: {
syncQuery (fields) {
if (!fields) err('empty fields')
switch (typeOf(fields)) {
case 'string':
this._syncQuery(defaultDescGen(fields))
break
case 'object':
this._syncQuery(mergeDesc(defaultDescGen(fields.localField), fields))
break
case 'array':
fields.forEach(field => this.syncQuery(field))
break
default:
err('invalid type of field')
}
},
_syncQuery ({ localField, queryField, local2query, query2local }) {
(() => {
// backup the default value
const defaultVal = this[localField]
// local ==(sync)==> query
this.$watch(localField, function (v, oldV) {
this.updateQuery({ [queryField]: local2query.formatter(v, oldV) })
}, local2query)
// local <==(sync)== query
this.$watch(`$route.query.${queryField}`, function (v, oldV) {
this[localField] = query2local.formatter(v, oldV) || defaultVal
}, query2local)
})()
}
}
}
/**
* default descriptor generator for $watch
* @param {String} field
* @return {Object}
*/
function defaultDescGen(field) {
return {
localField: field,
queryField: field,
local2query: {
formatter: v => v,
immediate: false,
deep: false
},
query2local: {
formatter: v => v,
immediate: true,
deep: false // P.S. watching deep of a string makes no sense
}
}
}