In a Vue.js component I want to display the user list:
This piece of code does set the tableData correctly after making the axios call.
export default {
data: function() {
return {
tableData: [],
tableColumns: [
{show: 'firstName', label: 'First Name', dataType: ''},
{show: 'lastName', label: 'Last Name', dataType: ''},
],
showFilter: true,
}
},
beforeMount: function(){
axios({
method: 'get',
url: '/api/admin/users',
dataType: 'json',
headers: {'X-Requested-With': 'XMLHttpRequest'},
})
.then( (response) => {
var status = response.status;
if(status == 200 || status == "200"){
console.log(response.data)
this.tableData = response.data
}
else{
alert("not 200");
this.tableData = response.data
}
})
.catch( (error) => {
console.log(error);
});
},
components: {
VueDataTable,
},
}
However, if I wrap the axios code piece into another function in another file, then it cannot return the response.data:
export default {
data: function() {
return {
tableData: [],
tableColumns: [
{show: 'firstName', label: 'First Name', dataType: ''},
{show: 'lastName', label: 'Last Name', dataType: ''},
],
showFilter: true,
}
},
beforeMount: function(){
this.tableData = Utils.getUserList()
},
components: {
VueDataTable,
},
}
In the file Utils.js, the function looks like this:
export function getUserList(data) {
axios({
method: 'get',
url: '/api/admin/users',
dataType: 'json',
headers: {'X-Requested-With': 'XMLHttpRequest'},
})
.then( (response) => {
var status = response.status;
if(status == 200 || status == "200"){
console.log(response.data)
data = response.data
}
else{
alert("not 200");
return;
}
})
.catch( (error) => {
console.log(error);
});
}
The function in Utils.js is actually executed and the response does get the data, the console.log(response.data) also gets printed out, but the return response.data CANNOT get executed, instead, the program jumps to the return statement in the else block. Very weird. I also tried to search online but could not find an example that wraps an axios request in an external file to be used by multiple components.
See Question&Answers more detail:
os