How to properly use Vue Router beforeRouteEnter or Watch to run a method in a Single File component?

I am working on an application in Vue.js using the Single File and Vue Router components. I have a search component where I need to execute a method to repopulate the search results every time a user visits a route. The method is executed correctly the first time the route is visited due to the "Create" hook:

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

      

However, when the user leaves the route (for example to register or log into the app) and return to the search page, I cannot find a way to automatically trigger this.initializeSearch () on subsequent visits.

The routes are configured in index.js as follows:

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 understand that I have to use "watch" or "beforeRouteEnter", but I can't seem to get myself to work.

I tried to use "look" like this in my Search component:

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

      

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

Any help on this would be much appreciated.

+3


source to share


1 answer


Since you want to repopulate the search results every time the user visits the route.

You can use beforeRouteEnter()

in your component like below:

beforeRouteEnter (to, from, next) { 
    next(vm => { 
        // access to component 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();
       next();
    }) 
} 

      



You can learn more about navigation guards here

Here is a working violin

+1


source







All Articles