You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 03:09:00