gpt4 book ai didi

javascript - 带有 Google Auth Signin 的 Vuejs 全局函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:49:43 24 4
gpt4 key购买 nike

我正在使用 vuejs 2,但在使用 Google 身份验证登录时遇到问题。

我使用 vue 成功设置并获得了注销和用户配置文件功能:

export default {

data() {
return {
user: null
};
},

methods: {
getUserProfile() {
const profile = gapi.auth2.currentUser.get().getBasicProfile();

console.log(profile.getIdToken());
},

signOut() {
const auth2 = gapi.auth2.getAuthInstance();

auth2.signOut().then(function () {
console.log('user signed out');
});
}
},
};

我这里的主要问题是 onSignIn(googleUser)功能来自

<div class="g-signin2" data-onsuccess="onSignIn"></div>

data-onsuccess="onSignIn"正在vue实例之外寻找一个js函数。我尝试添加 onSignIn(googleUser)在我的 HTML 文件中的功能如下:

<script>
function onSignIn(googleUser) {
const auth2 = gapi.auth2.init();

if (auth2.isSignedIn.get()) {
const profile = auth2.currentUser.get().getBasicProfile();

console.log(profile.getName());
console.log(googleUser.getAuthResponse().id_token);
console.log(googleUser.getAuthResponse().uid);
console.log(auth2.currentUser.get().getId());
}
}
</script>

这按预期工作,但我想知道是否可以将它添加到我的 vue 文件中而不是原生 javascript 方式,因为在这个函数中,我将调用其他 vue 方法。

或者有什么方法可以添加 onSignIn(googleUser)在 vue 中运行然后在 Google Auth 完成时调用它?

最佳答案

这里的解决方案是使用 gapi.signin2.render 在组件的 mounted Hook 中呈现登录按钮

<template>
<div id="google-signin-btn"></div>
</template>

<script>
export default {
methods: {
onSignIn (user) {
// do stuff, for example
const profile = user.getBasicProfile()
}
},
mounted() {
gapi.signin2.render('google-signin-btn', { // this is the button "id"
onsuccess: this.onSignIn // note, no "()" here
})
}
}
</script>

参见 https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid_options

关于javascript - 带有 Google Auth Signin 的 Vuejs 全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com