使用从聚合物2中的axios获取的数据改变数组时遇到问题



我正在试验与工作相关的原因聚合物2。我决定做一个无限卷轴。到目前为止,我知道如何在其他框架(如VUE)中做到这一点,但我有一点麻烦与聚合物

这个想法是从https://randomuser.me/

获取一些虚拟数据应用加载了一个名为" infinitesscroll -component";没有其他元素

可以毫不费力地获取数据并将其压入初始数组。一旦到达窗口的末端,它就会触发一个事件,该事件应该加载一个用户push将其放入初始数组并再次渲染。但它没有做到这一点。

这是我的代码:

<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-repeat.html">
<dom-module id="infinitescroll-component">
<template>
<style>
:host {
display: block;
margin: 15px;
}
</style>

<template is="dom-repeat" items="[[users]]" as="user">
<p>[[user.name.first]]</p>
<p>[[user.name.last]]</p>
<hr>
</template>
</template>
<!-- Importing Axios  -->
<!-- <script src="node_modules/axios/dist/axios.min.js"></script> why it doesnt work?-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- General Script -->
<script>
class InfiniteScroll extends Polymer.Element {
static get is() {
return 'infinitescroll-component';
}
static get properties() {
return {
users: {
type: Array,
value: function () {
return [];
}
},
arrayControl: {
type: Array,
value: function () {
return ['uno'];
}
},
controlador: {
type: String,
value: 'soy un controlador'
}
}
}

// Hook de inicio
connectedCallback() {
super.connectedCallback();
this.getInitialUsers();
}
getInitialUsers() {
axios.get(`https://randomuser.me/api/?results=20`).then((response) => {
this.users = response.data.results;
});
}
// -------------------------------------
ready() {
super.ready();
window.addEventListener('scroll', this.scrollDetection);
console.log(this.controlador);
console.log('ready ' + this.arrayControl);
}
funcionPrueba() {
this.push('arrayControlador', this.controlador);
console.log('esto es el array de control ' + this.arrayControl);
}
scrollDetection() {
let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight === document.documentElement.offsetHeight;
if (bottomOfWindow) {
axios.get(`https://randomuser.me/api/?results=`).then(response => {
//   PUSHING DATA INTO USERS ARRAY
console.log("axios Loads");
});

console.log("End of Scroll");
}
}

}
window.customElements.define(InfiniteScroll.is, InfiniteScroll);
</script>
</dom-module>

thanks in advance

尝试

this.push("用户",response.data.results);


我希望在用户通过滚动到达窗口末端时将数据推送到用户数组中-

好了,我找到错误了。

我必须绑定'this',这样它就不会错过作用域

window.addEventListener('scroll', this.scrollDetection.bind(this));

然后添加突变方法为:

this.push("users", response.data.results[5]);

希望这对将来的任何人都有帮助

最新更新