【问题标题】:specify condition before loading vuejs component在加载 vuejs 组件之前指定条件
【发布时间】:2022-01-12 14:45:29
【问题描述】:

我是 vuejs 新手,想在组件加载前做个检查,但不知道怎么做。

我想要做的是如果"this.$store.getters.user.id""this.$route.params.id" 在组件加载之前不相等 "this.$router.push({name: 'home', params: {id" : this.$store.getters.user.id}})"

{
        path: '/:id',
        name: 'home',
        component: () => import('../Views/Admin/Home.vue'),
        meta: {
            guard: 'auth'
        },
        children: [
            {
                path: 'admin',
                component: () => import('../Views/Admin/HomeProfile.vue'),
                name: 'admin',
                meta: {
                    guard: 'auth'
                },
            }
        ]
    },
router.beforeEach((to, from, next) => {

    if (store.getters.user) {
        if (to.matched.some(route => route.meta.guard === 'guest')) next({name: 'home'})
        else next();

    } else {
        if (to.matched.some(route => route.meta.guard === 'auth')) next({name: 'login'})
        else next();
    }
})

【问题讨论】:

  • 我该怎么做?路由器这样
  • 这可能会有所帮助:stackoverflow.com/a/70662676/10975709 这有点相关。在您的情况下,只需检查 store 而不是 checkAuth 函数并使用 meta 而不是路由名称。
  • 不,它根本没有帮助

标签: vue.js


【解决方案1】:

如果您需要在应用程序中的每个路由之前运行此函数,您可以使用路由器的beforeEach 函数来检查。

router.beforeEach((to, from, next) => { }.

如果这仅适用于一个或一些路由,您可以将属性 beforeEnter 设置为路由。 https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard


在你的 beforeEach 函数中,你需要进行你所说的验证。

if(this.$store.getters.user.id !== to.params.id) 
   next({
          name: 'home', 
          params: { id: this.$store.getters.user.id }
   });

【讨论】:

  • 我该怎么做?我编辑了主题,我不太了解
  • 我已经编辑了答案,试图为你添加一个例子。
猜你喜欢
  • 2017-12-09
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2019-10-28
  • 2020-01-19
  • 1970-01-01
  • 2019-12-25
  • 2018-12-24
相关资源
最近更新 更多