我正在使用单文件组件和 Vue 路由器在 Vue.js 中开发一个应用程序。我有一个搜索组件,每次用户访问该路线时,我都需要执行一个方法来重新填充搜索结果。由于“创建” Hook ,该方法在第一次访问路由时正确执行:
created: function() {
this.initializeSearch();
},
但是,当用户离开路线(例如注册或登录应用程序)并返回搜索页面时,我似乎无法找到在后续访问时自动触发 this.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”或“beforeRouteEnter”,但我似乎无法使用任何一个。
我尝试在我的搜索组件中像这样使用“watch”:
watch: {
// Call the method again if the route changes
'$route': 'initializeSearch'
}
而且我似乎找不到任何文档来解释如何在单个文件组件中正确使用 beforeRouteEnter 回调(vue-router 文档不是很清楚)。
如有任何帮助,我们将不胜感激。
最佳答案
因为您希望在用户每次访问该路线时重新填充搜索结果。
您可以在您的组件中使用 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();
})
}
您可以阅读更多关于导航守卫的信息here
关于vue.js - 如何正确使用 Vue Router beforeRouteEnter 或 Watch 来触发单文件组件中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041751/