Skip to content

Instantly share code, notes, and snippets.

@fuxingloh
Created January 13, 2020 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuxingloh/ce7879a83f8cfca54d83a25e5919379a to your computer and use it in GitHub Desktop.
Save fuxingloh/ce7879a83f8cfca54d83a25e5919379a to your computer and use it in GitHub Desktop.
A plugin for nuxtjs, changing browser url without overwriting query string or path.
<script>
export default {
mounted() {
// Replace place without changing querystring
this.$path.replace({path: '/path-name'})
// Replace query string without changing path
this.$path.replace({query: {'foo': 'bar'}})
}
}
</script>
export default {
...,
plugins: [
'~/plugins/path',
],
...
}
/**
* Path manipulation plugin.
* E.g: this.$path.replace({path: `/${slug}-${id}`})
* E.g: this.$path.replace({query: {foo:'bar'}})
*/
export default function (context, inject) {
inject('path', {
replace: ({path, query}) => {
const getPath = () => {
return path ? path : window.location.pathname;
}
const getQuery = () => {
if (query) {
if (Object.keys(query).length > 0) {
return '?' + Object.keys(query)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`)
.join('&');
}
return ''
}
return window.location.search || ''
}
window.history.replaceState({}, document.title, `${getPath()}${getQuery()}`)
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment