16

I'm working on an app in Vue.js using Single File Components and Vue Router. I have a Search component where I need to execute a method to re-populate search results each time a user visits the route. The method executes correctly the first time the route is visited because of the "create" hook:

created: function() {
    this.initializeSearch();
  },

However, when the user leaves the route (to register or log into the app for instance), and returns to the Search page, I can't seem to find a way to automatically trigger this.initializeSearch() on subsequent visits.

Routes are set up in index.js like so:

import Search from './components/Search.vue';
import Login from './components/Login.vue';
import Register from './components/Register.vue';

// Vue Router Setup
Vue.use(VueRouter)

const routes = [
  { path: '/', component: Search },
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  { path: '*', redirect: '/' }
]

export const router = new VueRouter({
  routes
})

I gather that I should be using "watch" or "beforeRouteEnter" but I can't seem to get either to work.

I tried using "watch" like so within my Search component:

watch: {
    // Call the method again if the route changes
    '$route': 'initializeSearch'
  }

And I can't seem to find any documentation explaining how to properly use the beforeRouteEnter callback with a single file component (the vue-router documentation isn't very clear).

Any help on this would be much appreciated.

Adam Sweeney
  • 161
  • 1
  • 1
  • 4

1 Answers1

21

Since you want to re-populate search results each time a user visits the route.

You can use beforeRouteEnter() in your component as below:

beforeRouteEnter (to, from, next) { 
  next(vm => { 
    // access to component's instance using `vm` .
    // this is done because this navigation guard is called before the component is created.            
    // clear your previously populated search results.            
    // re-populate search results
    vm.initializeSearch();
  }) 
} 

You can read more about navigation guards here

Here is the working fiddle

Dónal
  • 185,044
  • 174
  • 569
  • 824
Vamsi Krishna
  • 30,568
  • 8
  • 70
  • 78
  • 1
    @hipertracker added an example to my answer. Have a look. – Vamsi Krishna Apr 15 '18 at 11:57
  • How would one accomplish this inside a TypeScript class? I currently do `@Component({ beforeRouteEnter(to, from, next) { this.beforeRouteEnter(to, from, next); } }`, but that's not very clean, right? – Derk Jan Speelman Oct 01 '20 at 12:13
  • 1
    may I know how if we want to go specific router after evaluating `vm.checkPolicy()` for example, inside the `next` callback? – Andre Suchitra Jul 08 '21 at 04:05
  • 1
    Dead link for navigation guards. [Vue Router V4 Link](https://router.vuejs.org/guide/advanced/navigation-guards.html) – TheHiggsBroson Feb 09 '22 at 04:59