- Notifications
You must be signed in to change notification settings - Fork2
OneWayTech/vue-sync-query-mixin
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
vue-sync-query-mixin@1.x
see branchv1
Effortlessly keep local state and
$route.query
in sync for Vue 1.x | Vue 2.x
Intellectual property ofOneway.mobi
- Vue 1.x | 2.x
- Vue Router 0.7.x | 2.x
npm i vue-sync-query-mixin -S
alternatively:<script src="dist/vue-sync-query-mixin.min.js"></script>
which exposesVueSyncQuery
as a global variable
Vue 1.x online example ishere (source code is./example-vue1.html
)
Vue 2.x online example ishere (source code is./example-vue2.html
)
// This is a Vue componentimportsyncQueryfrom'vue-sync-query-mixin'exportdefault{mixins:[syncQuery],data:()=>({limit:10}),ready(){// `limit` will keep in sync with `$route.query.limit`this.syncQuery('limit')}// Vue 1.x can use beforeCompile/compiled/ready// Vue 2.x can use created/beforeMount/mounted}
syncQuery
accepts 4 types of argument:
string|string[]
this.syncQuery('limit')this.syncQuery(['limit'])
object|object[]
this.syncQuery({localField:'limit',queryField:'limit',local2query:{formatter:v=>v,immediate:false,deep:false},query2local:{formatter:v=>v,immediate:true,deep:false}})this.syncQuery([{localField:'limit',queryField:'limit',local2query:{formatter:v=>v,immediate:false,deep:false},query2local:{formatter:v=>v,immediate:true,deep:false}}])
More detail insource code
Vue.js officialvm.$watch( expOrFn, callback, [options] )
API documentation ishere
_syncQuery({ localField, queryField, local2query, query2local}){(()=>{// backup the default valueconstdefaultVal=this[localField]// local ==(sync)==> querythis.$watch(localField,function(v,oldV){this.updateQuery({[queryField]:local2query.formatter(v,oldV)})},local2query)// local <==(sync)== querythis.$watch(`$route.query.${queryField}`,function(v,oldV){this[localField]=query2local.formatter(v,oldV)||defaultVal},query2local)})()}
local <==(sync)== query
, default type isstring
, or else you need to writeformatter
yourself- default
local2query
andquery2local
shown as below:
/** * default descriptor generator for $watch *@param {String} field *@return {Object} */functiondefaultDescGen(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}}}
But they can befunction
type, and then we regard them as theformatter
What's more, all the options aremerge
notoverride
, for example:
syncQuery({localField:'limit',queryField:'limit',local2query:{immediate:true},query2local:v=>+v// string to number})// ↑ is same as ↓syncQuery({localField:field,queryField:field,local2query:{formatter:v=>v,immediate:true,// merge!deep:false},query2local:{formatter:v=>+v,// merge!immediate:true,deep:false}})
npm run build