-3
在Vue.js組件中,我想顯示用戶列表: 這段代碼在進行axios調用後會正確設置tableData。
Vue.js無法設置從外部axios響應返回的數據
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,
},
}
但是,如果我換行Axios公司代碼塊到另一個文件中的另一個功能,那麼就不能返回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,
},
}
在文件Utils.js,功能看起來是這樣的:
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);
});
}
在Utils.js功能在實際執行和響應不獲取數據,將執行console.log(response.data)也得到打印機d out,但返回response.data不能被執行,而是程序跳轉到else塊中的return語句。很奇怪。我也嘗試過在線搜索,但是找不到一個包含axios請求的例子,以供多個組件使用的外部文件。
如果您向我們提供了更多信息,例如您迄今爲止編寫的代碼,這將有所幫助。 –
https://stackoverflow.com/help/how-to-ask –
對不起,我沒有弄清楚如何在這裏發佈js代碼。現在它應該是有道理的。 –