Vue3中window.location.href静态赋值生效 变量赋值不跳转问题求解
问题根因
你的代码执行顺序出了问题,$store.dispatch 是异步API,调用后不会立刻执行then里的回调逻辑:
- 你写在
then外部的return window.location.href = this.navigationURL是同步代码,会先执行 - 执行赋值时
this.navigationURL还没有被接口返回值赋值,还是初始的空值/undefined,所以跳转失效,触发页面重载回退
修复方案
把跳转逻辑移动到then回调内部,保证拿到接口返回的跳转地址后再执行跳转操作,修正后的代码如下:
业务方法代码修改
authenticationChoice(recieved) { this.$store.state.gitSourceAuthenticationChoice = recieved; this.$store.dispatch("gitSourceAuthenticationURL").then((response) => { const navigationURL = response["oauth2_redirect"]; console.log(navigationURL); // 拿到地址后直接执行跳转 window.location.href = navigationURL; }); }
也可以用async/await 简化异步写法,逻辑更清晰:
async authenticationChoice(recieved) { this.$store.state.gitSourceAuthenticationChoice = recieved; const response = await this.$store.dispatch("gitSourceAuthenticationURL"); window.location.href = response["oauth2_redirect"]; }
可选优化:阻止按钮默认行为
如果修改后还是出现页面回退的情况,可以给点击事件添加.prevent修饰符,阻止按钮默认提交行为:
<button type= "button" @click.prevent="authenticationChoice(currentView['name'])">
内容的提问来源于stack exchange,提问作者MEAG
相关产品推荐
相关产品推荐

