简体   繁体   English

Nuxt.js:如何重定向内部方法

[英]Nuxt.js: how to redirect inside methods

I'm learning Nuxt.js and I'm puzzled by how difficult it seems to be to simply redirect a user to another page from a method that is triggered via a click.我正在学习 Nuxt.js,我对通过单击触发的方法简单地将用户重定向到另一个页面似乎有多么困难感到困惑。

Here is the set up: I'm using Nuxt Auth to authenticate users, once authenticated I want them to be forwarded away from the signup page to another route.这是设置:我正在使用 Nuxt Auth 对用户进行身份验证,一旦通过身份验证,我希望他们从注册页面转发到另一个路由。 I already have middleware set up that redirect logged-in users, but it is only triggered when I refresh the page, not when I first log them in.我已经设置了重定向登录用户的中间件,但它仅在我刷新页面时触发,而不是在我第一次登录时触发。

I have a method like this:我有这样的方法:

async login(event) {
   event.preventDefault()
   try {
      await this.$auth.loginWith('local', this.loginData)
      // this is where my redirect logic should go
   } catch(error) { ... }
}

So far I've tried using this.$nuxt.refresh() which doesn't do anything at all and I've also tried this.$router.push('/route') which seems to hang the page completely.到目前为止,我已经尝试使用this.$nuxt.refresh() ,它根本不做任何事情,我也尝试过this.$router.push('/route') ,它似乎完全挂起页面。 Ideally, I would prefer the refresh approach so that I don't have to specify the landing page for logged in users in multiple places, but I also need to know how to use redirections inside methods, I would have thought it should be the most simple operation imaginable and yet it seems to be difficult to find.理想情况下,我更喜欢refresh方法,这样我就不必为多个地方的登录用户指定登录页面,但我还需要知道如何在方法中使用重定向,我认为它应该是最简单的操作可以想象,但似乎很难找到。

Any tips would be highly appreciated!任何提示将不胜感激!

UPDATE:更新:

I've found a solution, although it's not an ideal one.我找到了一个解决方案,虽然它不是一个理想的解决方案。 I've added an if-statement into beforeCreate that checks this.$auth.loggedIn and if it's true, then it calls this.$auth.redirect('home') when "home" is defined in nuxt.config.js under auth redirect.我在beforeCreate中添加了一个 if 语句来检查this.$auth.loggedIn ,如果它是真的,那么当在nuxt.config.js下定义“home”时,它会调用this.$auth.redirect('home')授权重定向。 The reason this solution is not ideal is that it relies on the auth module (as opposed to being a general redirect mechanism).这个解决方案不理想的原因是它依赖于 auth 模块(而不是一般的重定向机制)。

There's a way in Nuxt to reload the page like so: Nuxt 中有一种方法可以像这样重新加载页面:

this.$router.go(0)

also you can find more information here你也可以在这里找到更多信息

if this.$router is not working try this如果 this.$router 不工作试试这个

this.$nuxt.$options.router.push(url);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM