Ada*_*ney 5 components watch vue.js vue-router
我正在使用单个文件组件和Vue路由器在Vue.js中开发应用程序.我有一个搜索组件,我需要在每次用户访问路径时执行一种方法来重新填充搜索结果.由于"create"挂钩,该方法在第一次访问路径时正确执行:
created: function() {
this.initializeSearch();
},
Run Code Online (Sandbox Code Playgroud)
但是,当用户离开路径(例如注册或登录应用程序)并返回"搜索"页面时,我似乎找不到在后续访问中自动触发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
})
Run Code Online (Sandbox Code Playgroud)
我认为我应该使用"watch"或"beforeRouteEnter",但我似乎无法工作.
我在我的搜索组件中尝试使用"watch":
watch: {
// Call the method again if the route changes
'$route': 'initializeSearch'
}
Run Code Online (Sandbox Code Playgroud)
而且我似乎找不到任何文档来解释如何正确使用带有单个文件组件的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();
next();
})
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关导航卫士的更多信息
这是工作的小提琴