In my frontend I want to redirect the user to an error view in case the initialization went wrong. For this purpose I've prepare a special error view that could be called via a specific route. To improve UX I don't want to replace the url with something like /error
, but I still want to take advantage of the vue router.
Do you have any idea how to achieve this?
There is a discussion in github: change current component used by router-view without changing current URL
However, the expecting function replaceView
is still unavailable so far.
I have the exactly same requirement as yours, and I find a workaround:
I have a route component called App.vue
(I use Quasar Framework). Its template looks like:
<template>
<div id="q-app">
<div v-if="$store.state.g.errorState">
<the-error-page>Error Message</the-error-page>
</div>
<router-view v-else />
</div>
</template>
I use vuex's global store state.g.errorState
to flag the error state. If it is true, display the error page, otherwise display the normal router view.
If I have a error in my page, I just commit the true value to state.g.errorState
:
<script>
export default {
data() {
// ...
},
beforeMount() {
if (somethingWrong) {
this.$store.commit('g/errorState', true)
}
}
}
</script>
Obviously, the state.g.errorState
value should be restored to false every time the route changes:
const Router = new VueRouter({
// ...
})
Router.beforeEach((to, from, next) => {
store.commit('g/errorState', false)
next()
})
You can use history.replaceState
. pushState and replaceState are what Vue Router uses internally to manipulate the URL. Observe what happens to the address bar when you enter this line in your browser's console..
history.replaceState({urlPath:'/some/page/on/stackoverflow'},"",'/some/page/on/stackoverflow')
Working inside an axios interceptor, this did the trick for me (still a hack)
if (error.response.status === 404) {
router.replace({ name: '404' });
history.replaceState({}, "Not Found", error.response.request.responseURL)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With