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

2023-12-30

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

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 https://router.vuejs.org/en/advanced/navigation-guards.html

这里是工作小提琴 https://jsfiddle.net/Lydf8ygL/2/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何正确使用Vue Router beforeRouteEnter或Watch来触发单文件组件中的方法? 的相关文章

随机推荐