问题描述
我是 vue js 的新手,并且已经尝试了几个小时来将 Airtable 数据导入到我的应用程序中。我希望有人能帮助我,因为我觉得我快到了!我正在使用 Airtable NPM 包来检索数据 - https://www.npmjs.com/package/airtable
<template>
<section id="cards-section" class="cards-section">
<div class="centered-container w-container">
<h1>{{ msg }}</h1>
<div class="cards-grid-container">
<Card />
<ul id="example-1">
<li v-for="item in recordsList" v-bind:key="item">
data here {{ item }}
</li>
</ul>
</div>
</div>
</section>
</template>
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",components: {
Card,},props: {
msg: String,data() {
return {
recordsList: [],};
},mounted() {
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",})
.firstPage(function (err,records) {
if (err) {
console.error(err);
return;
}
records.forEach( (record) => {
console.log(record.get("Name"));
return record.get("Name")
});
});
},};
</script>
<style scoped>
</style>
解决方法
查看您的代码,您可能已成功从 airtable 检索数据并在 console.log 中看到一些记录。
现在如何将它们从该函数内部获取到您的 Vue 实例:
我将向您展示两种方法来解决这个问题,并在稍后解释它们:
方法 1:使用对 self 的引用。
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",components: {
Card,},props: {
msg: String,data() {
return {
recordsList: [],};
},mounted() {
// create a reference to this vue instance here.
var self = this;
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",})
.firstPage(function (err,records) {
if (err) {
console.error(err);
return;
}
// now we can set the recordList of our
// vue instance:
self.recordsList = records;
});
},};
</script>
方法二:使用javascript箭头函数:
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",mounted() {
// no need to create a reference this time.
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",})
.firstPage( (err,records) => {
if (err) {
console.error(err);
return;
}
this.recordsList = records;
});
},};
</script>
现在出了什么问题?在第一个例子中,我们使用了一个普通的 javascript 匿名函数。 this
在普通的 javascript 匿名函数中并不是您所期望的。我们通过在某处定义对 this (var self = this) 的引用来解决这个问题,而不是尝试 this.recordsList,而是在我们的匿名函数中执行 self.recordsList。
Nem 对 javascript 语言的改进引入了另一种类型的函数,即箭头函数。这个函数的一个好处是这个函数内的 this
是你定义它的对象。所以,this
是我们的 vue 实例。现在我们没有问题,只需设置 this.recordsList 即可。
我忽略的其他解决方案是:
- 使用 Function.bind
- 异步/等待