我正在登录,但是登录方法成功后,我正在为
$router
对象推送一条路线,但它不起作用,有人可以帮助我吗?
我的代码:
doLogin(){
this.attemptLogin({...this.user}).then(function(){
this.$router.push('/')
} )
},
因此,登录方法按预期执行,但回调
this.$router.push('/')
未运行。
我的
attemptLogin
是一个动作,它的代码如下:
export const attemptLogin = ( {commit}, user) => {
return http.post('login', {
'email': user.email,
'password': user.password
}).then(response => {
return commit(types.setToken, response.data)
}).catch( e => console.log(e))
}
解决了,我将方法
this.$router.push()
从我的代码更改为this.$router.go('/')
。
感谢大家的评论。
您必须推送到名称或路径 试试这个:
this.$router.push({ path: '/' })
this.$router.push({ name: 'Home' })
就我而言,我发现我的
beforeRouteUpdate
不执行next()
方法
坏:
beforeRouteUpdate(to, from, next) {
/*
something...
*/
}
好:
beforeRouteUpdate(to, from, next) {
/*
something...
*/
next() // DO IT!
}
我知道这个话题有点老了,但是在遇到这个问题,特别是 Nuxt 和 Vue 时,我想提供一些可能对某些人有帮助的更新。
login() {
this.$auth.loginWith('local', {
data: {
username: this.username,
password: this.password,
}
});
this.$router.push({name: 'dashboard'});
}
我的代码最初是这样的,但我忘记确保我使用的是 Promise 或使用 Async / Await 方法。
正确的代码(就我而言)如下所示;
async login() {
await this.$auth.loginWith('local', {
data: {
username: this.username,
password: this.password,
}
});
this.$router.push({name: 'dashboard'});
}
正如我所说,如果有其他需要,您可以使用
.then()
等。但我不想不把它提供给可能需要它的人。我的菜鸟错误。
我也遇到了同样的问题。 $router.push('/') 似乎不起作用,因为我没有重定向,日志中也没有错误。我没有意识到的是,我有一个小中间件正在寻找是否设置了身份验证令牌。我在错误的商店里找了它,所以自然它总是会摔倒。如果有中间件,请记住查看中间件,因为它不会在 router.push() 上返回错误
我不太喜欢 $router.go 方法,因为它正在对页面进行完全刷新。
就我而言,它不起作用的原因是因为我在更新状态之前尝试将 $router.push 到受保护的路由。 *更具体地说,我依赖 Firebase onAuthStateChanged 来更新状态,并且在我无法控制的此操作之前尝试 $router.push 。 *
建议:
推送到“索引”等非受保护的路由,并使您的组件根据状态值做出反应。 (不是最好的方法)
希望有帮助。干杯
我也有同样的问题。确保您在路由器中设置了
mode: 'history'
实际上,您可以使用以下代码在Nuxtjs中更改路由。
this.$router.push("/");
or
this.$router.push({ path: '/'} );
假设,如果您现在查看此链接“http://localhost:3000”或“http://192.168.0.102:300”并尝试使用给定代码推送来路由“/”来更改路由。所以它不会工作。因为,您已经查看了这条路线。所以,Nuxtjs的路线不能不改变。
为了处理这种情况,您可以在方法中使用以下技术/代码:
vuejs方式:
if($route.path == '/') {
//following 2 line code are sample code here put your need codes
this.isLogin = false;
this.user_full_name = 'My Account';
} else {
// this.$router.push("/");
this.$router.push({ path: '/'} );
}
=================================================
nuxtjs方式:
if($nuxt.$route.path == '/') {
//following 2 line code are sample code here put your need codes
this.isLogin = false;
this.user_full_name = 'My Account';
} else {
// this.$router.push("/");
this.$router.push({ path: '/'} );
}
我使用
this
从全局范围中获取了全局 that = this
的副本,然后使用了 that.$router.push('/path')
这对我有用!
就我而言,我必须将
async
关键字添加到组件脚本标签中:
<script async setup>
之前:
doLogin(){
this.attemptLogin({...this.user})
.then(function(){
this.$router.push('/')
} )
},
之后:
doLogin(){
this.attemptLogin({...this.user})
.then(() => {
this.$router.push('/')
} )
},