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

Vue2中全局函数能否访问组件局部变量/方法?(Google Identity SSO)

问题:Vue中Google Identity SSO全局回调无法访问组件内部变量/方法

我在使用新版Google Identity SSO时,参考其他方案用globalThis定义回调函数,成功避免了*[GSI_LOGGER]: The value of 'callback' is not a function. Configuration ignored*错误,初始实现代码如下:

<script>
export default {
  data: () => ({ error: false }),

  methods: {
    login() {
    },
  },
};

globalThis.googlelogin = function(response) {
}
</script>

<template>
<div>

<div id="g_id_onload"
data-client_id="xxx.apps.googleusercontent.com"         
data-auto_prompt="false"
data-callback="googlelogin"
data-auto_select="true">
</div>

{{ error }}
</div>
</template>

但遇到了新问题:某些场景下需要设置组件内的error变量来显示屏幕提示,可在globalThis.googlelogin里用this.error = 'xyz'完全无效——这里的this指向全局作用域,而且没法给这个回调传递额外参数。

把error改成全局变量或许能解决,但我不想大幅修改他人代码(我是Vue新手)。更理想的是让googlelogin能调用组件内部的login方法,但直接用this.login()也无法实现。

解决方案:使用EventBus

查找资料时我找到了可行方案,通过EventBus实现全局回调与组件内部方法的通信:

import Vue from 'vue'
const EventBus = new Vue();

export default {
  methods: {
    mycode(response) {
      // 在这里处理response,比如设置error变量或调用login方法
      this.error = '登录失败'
      // this.login()
    }
  },

  created() {
    EventBus.$on("callmycode", this.mycode);
  },
};

globalThis.googlelogin = function(response)
{
  EventBus.$emit("callmycode", response);
}

内容的提问来源于stack exchange,提问作者Martin Twigg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:02:40