【发布时间】:2018-11-07 09:18:11
【问题描述】:
This question 封装了我想做的事情,除了我想更进一步。我想在我的 VueJS 应用程序中使用单个 'fetchData' 函数来获取几个不同的 JSON 文件,这样我就不必为每个文件重复代码。这是相关的sn-p:
var app = new Vue({
el: '#app',
data: {
"theFirstJsonFile": {},
"theSecondJsonFile": {},
"theThirdJsonFile": {}
},
mounted() {
this.fetchData("database/firstFile.json", "theFirstJsonFile");
this.fetchData("database/secondFile.json", "theSecondJsonFile");
this.fetchData("database/thirdFile.json", "theThirdJsonFile");
},
methods: {
fetchData(theDataFile, containerObject) {
var vm = this;
$.getJSON(theDataFile, function(thisData) {
vm.containerObject = thisData;
console.log(thisData);
console.log(vm.containerObject);
})
.done(function() {
console.log( "Success loading "+theDataFile );
})
.fail(function() {
console.log( "Error loading "+theDataFile );
})
.always(function() {
console.log( "Completed" );
});
}
});
两个“console.log”调用都显示了获取的数据,但容器对象本身仍然是空的。我意识到我将第二个参数作为字符串而不是数据对象传递;我最初使用的是“this.theFirstJsonFile”(不带引号),但鉴于我在 fetchData 函数中定义了 var vm = this,它现在是多余的。如何以等同于“this.theFirstJsonFile”、“this.theSecondJsonFile”等的方式在我的函数中引用适当的 Vue 数据对象?
【问题讨论】:
-
请尝试
vm[containerObject] = thisData -
哇,简单的解决方案。想把它作为一个答案,这样我就可以给你功劳了吗?
-
更新了答案