javascript - 如何使用 Vue.js 初始化 google OAuth 客户端?

标签 javascript vue.js google-api google-oauth

我正在尝试将 google OAuth api 与 Vue.js 结合使用。 我使用并修改了谷歌提供的示例代码。 但是当我点击“授权”按钮时,控制台返回:

Uncaught TypeError: Cannot read property 'init' of undefined

at Vue$3.initClient (vueAuth.js:24)

at Vue$3.boundFn [as initClient] (vue.js:196)

at Vue$3.handleClientLoad (vueAuth.js:20)

at boundFn (vue.js:196)

at invoker (vue.js:2006)

at HTMLButtonElement.fn._withTask.fn._withTask (vue.js:1804)

这是我的代码

索引.html

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>管理画面</title>
</head>

<body>
    <p>Google Sheets API Quickstart</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <div id="app">
        <button @click="handleClientLoad">Authorize</button>
        {{ memberlist }}
    </div>

    <script async defer src="https://apis.google.com/js/api.js"></script>
    <script src="https://unpkg.com/vue"></script>
    <!-- vueAuth.js is my code -->
    <script src="vueAuth.js"></script>
</body>

</html>

vueAuth.js

// Client ID and API key from the Developer Console
const CLIENT_ID = '/*my client id */';

// Array of API discovery doc URLs for APIs used by the quickstart
const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/sheets/v4/rest"];

// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";

let vm = new Vue({
    el: '#app',

    data: {
        memberlist: ''
    },

    methods: {
        handleClientLoad: function () {
            gapi.load('client:auth2', this.initClient(this));
        },

        initClient: function (vue) {
            gapi.client.init({
                discoveryDocs: DISCOVERY_DOCS,
                clientId: CLIENT_ID,
                scope: SCOPES
            }).then(function () {
                // Listen for sign-in state changes.
                gapi.auth2.getAuthInstance().isSignedIn.listen(vue.updateSigninStatus);

                // Handle the initial sign-in state.
                vue.updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
                vue.handleAuthClick();
            });
        },

        updateSigninStatus: function (isSignedIn) {
            if (isSignedIn) {
                this.loadSheetsApi();
            } else {
                return;
            }
        },

        handleAuthClick: function (event) {
            gapi.auth2.getAuthInstance().signIn();
        },

        handleSignoutClick: function (event) {
            gapi.auth2.getAuthInstance().signOut();
        },

        loadSheetsApi: function () {
            var discoveryUrl =
                'https://sheets.googleapis.com/$discovery/rest?version=v4';
            gapi.client.load(discoveryUrl).then(this.listMajors);
        },

        listMajors: function () {
            gapi.client.sheets.spreadsheets.values.get({
                spreadsheetId: '/* my sheet id */',
                range: '/* target range */',
            }).then(function (response) {
                this.memberlist = response.result;
            })
        }
    }
})

我想知道为什么 gapi.client.init 不可用。 我应该如何更改我的代码以启用 gapi?

最佳答案

以防其他人正在寻找这个。这就是我为我的添加到日历按钮所做的

public/index.html在头部添加脚本

<head>
...
<script async defer src="https://apis.google.com/js/api.js"></script>
...
</head>

模板:

<ion-button @click="addToCalendar(item)">
  Add to Calendar <ion-icon :icon="calendarClearOutline"></ion-icon>
</ion-button>

脚本:

// after imports
var gapi = window.gapi;
var CLIENT_ID = "_YOUR_CLIENT_ID_";
var API_KEY = "_YOUR_API_KEY_";
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
var SCOPES = "https://www.googleapis.com/auth/calendar";

// in methods
    addToCalendar(event) {
      gapi.load("client:auth2", () => {
        console.log("gapi loaded", gapi.client);
    
        gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
        }).then(() => {
          const gcEvent = {
            "summary": event.eventName,
            "location": event.venue,
            "start": {
              "dateTime": moment(event.start).utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]"),
              "timeZone": "Africa/Johannesburg"
            },
            "end": {
              "dateTime": moment(event.end).utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]"),
              "timeZone": "Africa/Johannesburg"
            },
            "reminders": {
              "useDefault": false,
              "overrides": [
                {"method": "email", "minutes": 24 * 60},
                {"method": "popup", "minutes": 10}
              ]
            }
          };
    
          var request = gapi.client.calendar.events.insert({
            'calendarId': 'primary',
            'resource': gcEvent,
          });
    
          // window object is undefined inside `execute`/
          const rootWindow = window;
    
          request.execute(gcEvent => {
            rootWindow.open(gcEvent.htmlLink);
          })
        })
      })
    }

仅使用 moment(event.start).utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]") 如果您的 dates are not ISO

Grant Singleton 的 react tutorial帮助很大。

关于javascript - 如何使用 Vue.js 初始化 google OAuth 客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48810139/

相关文章:

javascript - ExTJS:如何获取所有可点击和可编辑的组件(按钮、触发器、文本字段等)?

javascript - Vue - 设置一个元素的宽度等于另一个元素的宽度

node.js - 将 google-api-javascript-client 与 node.js 结合使用

Node.js 简单 Google API 请求 : error:0906D06C:PEM routines:PEM_read_bio:no start line

javascript - 在 vue.js 中创建一个包含数据的 obj 名称

node.js - 有没有办法授予我的nodejs应用程序访问我的谷歌日历的权限?

javascript - 引用错误 : exit is not defined at repl:1:1 (in node. js)

javascript - 如何关闭使用 browser.windows.create() 打开的窗口?

javascript - 让 js 过滤器工作以显示菜单

javascript - 为什么我必须从一个模块传播 Vuex getter,而不是从另一个模块传播 Vuex getter?