How to Properly Use Vue Router beforeRouteEnter or Watch to trigger method in Single File Component?

前端 未结 1 824
孤街浪徒
孤街浪徒 2021-02-19 17:47

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

1条回答
  •  失恋的感觉
    2021-02-19 18:39

    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();
        next();
      }) 
    } 
    

    You can read more about navigation guards here

    Here is the working fiddle

    0 讨论(0)
提交回复
热议问题