Last active
November 3, 2017 13:56
-
-
Save cb109/847c89695a1bd96fcd49c040b6800ff6 to your computer and use it in GitHub Desktop.
vue-router: Map state to URL query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A Vue mixin to map local component state to URL query. | |
* | |
* Uses vue-router's $route.query to get/set the query params. | |
* | |
* Useful e.g. to store and restore filters to/from the URL. | |
* | |
*/ | |
var urlState = { | |
data() { | |
return { | |
paramToUnwatcher: [], | |
}; | |
}, | |
watch: { | |
// Is extended/managed dynamically. | |
}, | |
methods: { | |
syncToUrl(param, | |
urlParam=null, | |
transformCallback=null) { | |
if (urlParam === null) { | |
urlParam = param; | |
} | |
const unwatch = this.$watch(param, value => { | |
if (transformCallback !== null) { | |
value = transformCallback(value); | |
} | |
let query = Object.assign({}, this.$route.query); | |
if (value) { | |
query[urlParam] = value; | |
} | |
else { | |
delete query[urlParam]; | |
} | |
this.$router.push({'query': query}); | |
}); | |
this.paramToUnwatcher[param] = unwatch; | |
}, | |
removeSyncToUrl(param) { | |
let unwatch = this.paramToUnwatcher[param]; | |
if (unwatch) { | |
unwatch(); | |
} | |
}, | |
}, | |
}; | |
export default urlState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment