RomkaLTU
RomkaLTU

Reputation: 4129

VueJS Router prevent back on certains router-link's

Building PWA app with VueJS and I have tabs like navigation component. But instead of show/hide content, navigation is done through Vue Router. Side effect of this navigation is "back" button behavior, every navigation action is logged in browser history, after I visit 4 tabs, and if I want to go back to actual page which was before page with tabs, I need to press "back" 4 or more times (depends on how many times I navigated trough tabs).

What I want to do is something like this:

<router-link no-history="true" to="tab1">Tab1</router-link>
<router-link no-history="true" to="tab2">Tab2</router-link>
<router-link no-history="true" to="tab3">Tab3</router-link>

Of course, I don't want to do it globally. If this even possible?

Upvotes: 3

Views: 4408

Answers (2)

Abdelillah Aissani
Abdelillah Aissani

Reputation: 3108

add replace to your router-link to avoid stacking routes on the navigation history :

Vue.config.productionTip = false;
Vue.config.devtools = false;

const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }


const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]


const router = new VueRouter({
  routes 
})


const app = new Vue({
  router
}).$mount('#app')
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h5>Navigate between routes then click "previous"</h5>
  <button @click="$router.go(-1)">Previous</button>
  <p>
    <router-link to="/foo" replace>Go to Foo</router-link>
    <router-link to="/bar" replace>Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>

Upvotes: 0

F&#233;lix
F&#233;lix

Reputation: 408

You need to use router.replace.

From Vue Documentation :

It acts like router.push, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry.

In your case, you would just need to add the replace attribute to your router-link tag :

<router-link to="tab3" replace>Tab3</router-link>

You can find more informations about replace on Vue programmatic navigation doc

Upvotes: 3

Related Questions