如何使用Vue.js初始化Google OAuth客户端?

时间:2018-02-15 14:57:32

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

我尝试使用google OAuth api和Vue.js. 我使用和修改google供应的示例代码。 但是当我点击"授权"按钮,控制台返回:

  

未捕获的TypeError:无法读取属性' init'未定义的

     

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

     

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

     

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

     

at boundFn(vue.js:196)

     

在调用者(vue.js:2006)

     

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

这是我的代码

的index.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?

3 个答案:

答案 0 :(得分:0)

如果您的代码依赖Gapi来工作,则不应使用异步方式加载它。 在您的情况下加载它的正确方法是: <script src="https://apis.google.com/js/platform.js"></script>

答案 1 :(得分:0)

为您的脚本标签尝试以下操作:

<script src="https://apis.google.com/js/client.js"></script>

答案 2 :(得分:0)

如果其他人正在寻找这个。这是我为添加到Caledndar 按钮

做的事情

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);
          })
        })
      })
    }

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

格兰特·辛格尔顿的反应tutorial很有帮助。

相关问题