Created
January 13, 2020 16:00
-
-
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.
This file contains 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
<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> |
This file contains 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
export default { | |
..., | |
plugins: [ | |
'~/plugins/path', | |
], | |
... | |
} |
This file contains 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
/** | |
* 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