【发布时间】:2022-02-20 19:40:00
【问题描述】:
我正在使用 Alpine.data 全局变量,我希望在我的 loadJobs 方法触发时连接数组。我对 JS 中的代理不熟悉,我也不太明白为什么我的 data 属性返回的是 Proxy 对象而不是简单的数组。
这是我正在使用的代码:
jobState = {
low: 5,
high: 10,
isLoaded: false
}
document.addEventListener("alpine:init", () => {
Alpine.data("loadMoreJobs", () => ({
data: [],
loadJobs() {
// Update jobState
jobState.low = jobState.high
jobState.high += 5
const requestParams = {
dataType: 'json',
method: 'GET'
}
fetch(`http://127.0.0.1:3000/jobs/list/${jobState.low}/${jobState.high}`, requestParams)
.then((data) => {
return data.json()
})
.then((data) => {
this.data = [...this.data, data]
})
}
}))
})
【问题讨论】:
-
不认为你已经弄明白了?我现在自己也在苦苦挣扎!!
-
我找到了一种非常肮脏的伎俩,但它的工作原理:
// I have the data variable containing JSON back from the API call this.data = JSON.parse(JSON.stringify(this.data)); data = JSON.parse(JSON.stringify(data)); this.data = this.data.concat(data); -
我最初问是因为看起来您的问题与我的问题有关。经过更多调查,我认为不是。数据(您的数组)包含在
Proxy()中这一事实一点也不重要——您仍然可以将其视为一个数组。如果不能,则代码中可能存在更根本的问题(由于您将名称data既用作参数又用作类变量!)。我还在旅行中发现parse(stringify(data))解决方案只是一种弥补裂缝的方法。您的代码中很可能存在更根本的错误。 -
感谢您的回答,我读到这确实不重要。我在示例中更改了变量名称以使其清楚,但在我的代码中没有以这种方式调用它们,所以我猜你所指的地方还有另一个错误。也许您应该添加您的评论作为我问题的答案,以便我接受?
标签: javascript alpine.js