前端 vue 实现 Google账户登录 功能

2,885 阅读1分钟

Google账户登录

1. 获取网页应用的配置代码段

要获取网页应用的配置代码段,请执行以下操作:

  • 登录 Firebase,然后打开您的项目。
  • 在概览页面上,点击添加应用。
  • 选择将 Firebase 添加到您的网页应用。
  • 复制该代码段并将其添加到应用的 HTML 中。

firebase.google.com/docs/auth/w…

console.firebase.google.com/

1672816181220.jpg

找到项目配置

选择网页开发,点下面的小图标

1672815198903.jpg

填写名字点击注册即可

cfa87341dd3d09e5dd10845d22fa74d.png

下载 npm install firebase

然后将'针对要使用的产品来初始化 Firebase 并开始使用相应 SDK.'贴到自己的方法里,点击调用即可

ecfddaa44e20ccb1135c9860be04643.png

添加Google登录

1672815254575.jpg

b4905169d471b04552d9addedfc4f03.png

ab40c92d9b8b283da8a590cc0d923b4.png

a6ef891328a662c7fb3afbd1d0cc119.png

然后就可以使用google账户登录了

  • 如果注册了找不到,在项目设置里面下滑,找到'您的应用', 复制firebaseConfig就可以替换了

5b111b6f66412fef0deae53ab5b620d.png

  • 全部代码

utils.js

  // Google 登录
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";

export function googleLogin() {
  const firebaseConfig = { // 这里替换成你的
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  }
  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const provider = new GoogleAuthProvider();
  const auth = getAuth();
  signInWithPopup(auth, provider)
    .then((result) => {
      // This gives you a Google Access Token. You can use it to access the Google API.
      const credential = GoogleAuthProvider.credentialFromResult(result);
      const token = credential.accessToken;
      // The signed-in user info.
      const user = result.user;
      console.log('已登录的用户信息:',user)
      // ...
    }).catch((error) => {
      // 此处处理错误。
      const errorCode = error.code;
      const errorMessage = error.message;
      // 使用的用户帐户的电子邮件。
      const email = error.customData.email;
      // 使用的AuthCredential类型。
      const credential = GoogleAuthProvider.credentialFromError(error);
      // ...
    });
}

view.vue

<template>
  <div @click="onclick">使用谷歌登录</div>
</template>

<script>
import { googleLogin } from '../utils/util.js'
export default {
  methods: {
    onclick() {
      googleLogin()
    }
  }
}
</script>

<style>

</style>