簡體   English   中英

VueJS 組件在獲取數據時無法呈現

[英]VueJS Component failing to render when fetching data

我是 Vue.JS 和 JavaScript 的新手,所以我調試這些應用程序的時候很糟糕,特別是使用 Promise 和異步工具。 我正在嘗試構建我的第一個從某處獲取數據的 Vue 組件。 我正在使用 Google 表格 API 並返回樣本表的一些單元格。 我的組件如下所示:

<template>
<ul>
  <li v-for="athlete in athletes" :key="athlete">
    {{ athlete }}
  </li>
</ul>
</template>

<script>
import readCopaPinheiros from '@/sheets/fetchData.js';

export default {
  name: 'AthletesTable',
  data () {
    return {
      loading: false,
      athletes: null
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.loading = true;
      readCopaPinheiros('inscritos').then(values => {
        this.loading = false;
        console.log(values)
        this.athletes = values
      });
    },
  } 
}
</script>

<style>
</style>

編輯 1

fetchData 腳本:

const fs = require('fs');
const { google } = require('googleapis');
const TOKEN_PATH = '';
const CREDENTIALS_PATH = ''

const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, 'utf-8'));

const {
client_secret: clientSecret,
client_id: clientId,
redirect_uris: redirectUris,
} = credentials.installed;

const oAuth2Client = new google.auth.OAuth2(
  clientId, clientSecret, redirectUris[0],
);

const token = fs.readFileSync(TOKEN_PATH, 'utf-8');
oAuth2Client.setCredentials(JSON.parse(token));

async function readSheet(spreadsheetId, range) {
  const sheets = google.sheets({ version: 'v4', auth: oAuth2Client });

  return sheets.spreadsheets.values.get({
    spreadsheetId,
    range,
  })
  .then(res => res.data.values)
  .catch(err => console.log('Opa! Erro:', err));
}

function readSheetJsnofied(spreadsheetId, range) {
    return readSheet(spreadsheetId, range)
      .then(values => jsonifySheet(values));
}

function jsonifySheet(sheetValues) {
  const header = sheetValues[0];
  const values = sheetValues.slice(1);
  return values.map((row) => {
    const rowObj = ({});
    for (let i=0; i < row.length; i++) rowObj[header[i]] = row[i];
    return rowObj;
  });
}

const readCopaPinheiros = d => readSheetJsnofied('sheetId', d);

export default readCopaPinheiros

由於某種原因,組件不呈現。 我什至不知道該怎么做才能調試,我所有的控制台日志嘗試都不會在控制台上打印一些東西。 有人可以幫我理解出了什么問題嗎?

編輯 2

此錯誤僅在嘗試獲取數據時出現: 在此處輸入圖像描述 當我嘗試直接在數據 function 中使用帶有假值的占位符列表時,它可以工作。 我不認為這是渲染本身的問題,而是它如何與 created 和 fetchData 函數交互。

v-for="athlete in athletes"

此代碼僅在athletes為數組時有效。 最初,您將其設置為 null,因此在來自 api 的數據到達之前,它將是 null。 但是該組件仍會嘗試使用您的null運動員渲染該組件,並且會出錯。 您可以嘗試使用此解決方案:

data () {
  return {
      loading: false,
      athletes: []
  }
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM