vue.js - 如何正确使用 Vue Router beforeRouteEnter 或 Watch 来触发单文件组件中的方法?

标签 vue.js components watch vue-router

我正在使用单文件组件和 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

这是 working fiddle

关于vue.js - 如何正确使用 Vue Router beforeRouteEnter 或 Watch 来触发单文件组件中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041751/

相关文章:

javascript - 每次弹出模态时,如何在模态内的按钮上设置自动对焦?

apache-flex - 如何从Flex中的自定义 View 访问父容器的数据?

javascript - Angular.js 中的 "scope.watch is not a function"错误

Python从其他源连续读取stdin

html - 无法在父行 bootstrap 4 和 VueJs 中获取两行

vue.js - 如何使 vuetify 对话框可拖动

javascript - 使用 Vue JS 从计算属性中获取选择选项

javascript - react 不通过 Prop 将状态传递给 child

delphi - 循环 TabSheet 上的所有组件

node.js - 使用 docker 在更改的文件上停止使用 vscode 中的 --watch 调试 nestjs 应用程序