Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change vue router route without changing the URL

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?

like image 444
jimmy Avatar asked Oct 24 '18 10:10

jimmy


3 Answers

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()
})
like image 193
guogangj Avatar answered Nov 11 '22 13:11

guogangj


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')

like image 20
Husam Ibrahim Avatar answered Nov 11 '22 12:11

Husam Ibrahim


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)
    }
like image 5
vicovicovico Avatar answered Nov 11 '22 11:11

vicovicovico