在无限滚动问题javascript中我有错误
无法读取未定义的属性(读取“人”)表达式:“$store.products.people”。
在滚动时尝试获取 API endpint 中的每 5 个项目。但是提取是正确的,并且设置了 people 数组。我哪里错了?
https://codesandbox.io/s/onscroll-izfjoc?file=/index.htm**
// html
<div x-data @scroll="$store.products.goScroll()">
//script js
people: [],
getAllProducts(searchInput, num = 5) {
this.loading = true;
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((res) => {
let local = this;
this.people = res.slice(0, num);
});
}
// scrolling function
goScroll: window.document
.querySelector(".content__mid-wrapper")
.addEventListener("scroll", () => {
const {
scrollTop,
scrollHeight,
clientHeight
} = window.document.documentElement.querySelector(
".content__mid-wrapper"
);
if (clientHeight + scrollTop >= scrollHeight) {
let local = this;
local.getAllProducts();
}
})
错误消息表明
people
的$store.products
属性在表达式$store.products.people
被求值的地方是未定义的。
根据提供的代码,
getAllProducts
方法似乎负责设置 people
数组。但是,从代码片段中并不清楚是否在触发滚动事件监听器之前调用了此方法。
要解决此问题,您可以在代码中添加一些 console.log 语句,以跟踪程序执行期间各个点的 people 数组和
$store.products
对象的值。例如,您可以在getAllProducts
方法中添加以下语句:
console.log("Response data:", res);
console.log("People array:", this.people);
console.log("$store.products:", $store.products);
这将帮助您确定
getAllProducts
方法是否正确设置了 people 数组,以及 $store.products
对象是否被正确初始化。
另一个可能的问题是没有使用正确的 this 上下文调用
goScroll
函数。在当前的实现中,goScroll 函数中的 this 指的是 window.document
对象,它无权访问 getAllProducts
方法。要解决此问题,您可以使用箭头函数或 bind 方法将 goScroll
函数的 this 上下文绑定到 Vue 实例:
goScroll: function() {
const vm = this; // save the Vue instance to a variable
window.document
.querySelector(".content__mid-wrapper")
.addEventListener("scroll", function() {
const {
scrollTop,
scrollHeight,
clientHeight
} = this.documentElement.querySelector(
".content__mid-wrapper"
);
if (clientHeight + scrollTop >= scrollHeight) {
vm.getAllProducts(); // use the saved Vue instance
}
});
}.bind(this),
有了这个变化,事件监听器中的 this 将引用 Vue 实例,它可以访问
getAllProducts
方法和 people
数组。
我希望这可以帮助您解决问题!