Vue.js 在单文件组件中,如何在RouteEnter或Watch to trigger方法之前正确使用Vue路由器?

Vue.js 在单文件组件中,如何在RouteEnter或Watch to trigger方法之前正确使用Vue路由器?,vue.js,components,watch,vue-router,Vue.js,Components,Watch,Vue Router,我正在Vue.js中使用单文件组件和Vue路由器开发一个应用程序。我有一个搜索组件,每次用户访问路线时,我都需要执行一个方法来重新填充搜索结果。由于“创建”钩子,该方法在第一次访问路由时正确执行: 但是,当用户离开路线(例如注册或登录应用程序)并返回到搜索页面时,我似乎找不到在后续访问中自动触发此.initializeSearch()的方法 在index.js中设置路由,如下所示: import Search from './components/Search.vue'; import Logi

我正在Vue.js中使用单文件组件和Vue路由器开发一个应用程序。我有一个搜索组件,每次用户访问路线时,我都需要执行一个方法来重新填充搜索结果。由于“创建”钩子,该方法在第一次访问路由时正确执行:

但是,当用户离开路线(例如注册或登录应用程序)并返回到搜索页面时,我似乎找不到在后续访问中自动触发此.initializeSearch()的方法

在index.js中设置路由,如下所示:

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
})
我想我应该使用“watch”或“beforewouteenter”,但我似乎无法让这两个词都起作用

我尝试在搜索组件中使用“watch”这样的功能:

watch: {
    // Call the method again if the route changes
    '$route': 'initializeSearch'
  }
而且我似乎找不到任何文档来解释如何正确使用带有单个文件组件的beforeRouteEnter回调(vue路由器文档不是很清楚)


非常感谢您在这方面提供的任何帮助。

因为您希望在用户每次访问路线时重新填充搜索结果

您可以在组件中使用beforeRouteEnter(),如下所示:

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();
  }) 
} 
您可以阅读有关导航卫士的更多信息


以下是您为@hipertracker缓存路由时使用的

,在我的回答中添加了一个示例。看看,在一个TypeScript类中如何实现这一点?我现在做
@Component({beforeRouteEnter(to,from,next){this.beforeRouteEnter(to,from,next);}}
,但这不是很干净,对吗?
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();
  }) 
}