This question encapsulates what I want to do, except I'd like to take it a step further. I want to use a single 'fetchData' function in my VueJS application to grab several different JSON files so I don't have to repeat the code for each file. Here's the relevant snippet:
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" );
});
}
});
Both 'console.log' calls show the fetched data, but the container object itself remains emtpy. I realize I'm passing in the second argument as a string rather than as a data object; I was originally using 'this.theFirstJsonFile' (without quotes), but given that I'm defining var vm = this inside the fetchData function, it's now redundant. How do I reference the appropriate Vue data object inside my function in a way that equates to 'this.theFirstJsonFile', 'this.theSecondJsonFile', etc.?
答案 0 :(得分:0)
containerObject
是一个变量。要访问它,您需要使用方括号:
vm[containerObject] = thisData
更多详情:
var containerObject = "theFirstJsonFile"
vm[containerObject] // === vm.theFirstJsonFile
vm.containerObject // === vm.containerObject