【发布时间】:2018-10-11 15:26:44
【问题描述】:
案例: 我正在网站上进行无限滚动,当表格底部从外部到达视口底部时,表格必须加载更多行)
代码 为此,首先我在数据中设置了一个 windowHeight 变量,在创建的 lifehook 中我首先将其设置为 window.innerheight 并在窗口对象上添加了一个调整大小事件监听器以将 windowHeight 变量设置为当前的 window.innerheight,例如这个:
data() {
return {
windowHeight: 0,
}
}
created() {
this.windowHeight = window.innerHeight;
window.addEventListener('resize', () => {
this.windowHeight = window.innerHeight
})
}
然后我设置了一个名为 topRect 的变量并将其设置为我放置在模板上的表格之后的 div 的 topRect,因此当该元素的 topRect 低于窗口内部高度时,它必须触发一个方法来加载更多数据,我是这样做的:
脚本
data() {
return {
windowHeight: 0,
topRect: 0,
divAfterTable: '',
}
}
created() {
this.windowHeight = window.innerHeight;
window.addEventListener('resize', () => {
this.windowHeight = window.innerHeight
})
}
mounted() {
this.divAfterTable = document.querySelector(#div-after-table)
this.topRect = this.divAfterTable.getBoundingClientRect().top;
window.addEventListener('scroll', this.setClientRect)
})
}
methods: {
setClientRects() {
this.topRect = this.divAfterTable.getBoundingClientRect().top;
}
}
模板
<template>
<div class="table">
<div class="table__container">
<table class="table__fixture">
<thead>
<tr>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</thead>
<tbody>
<tr v-if="tableData.data" v-for="row in tableData" :key="row.id">
<td>{{row.colOne}}</td>
<td>{{row.colTwo}}</td>
<td>{{row.colThree}}</td>
</tr>
</tbody>
</table>
</div>
<div id="div-after-table"></div>
</div>
</template>
该功能的其余代码无关紧要。
预期行为:
setClientRect 方法应该在滚动时触发并更新 topRect 变量,但它不会,它只是在调整窗口大小时触发,奇怪的是我在里面放了一个 console.log('it works') setClientRects 方法如下:
methods: {
setClientRects() {
this.topRect = this.divAfterTable.getBoundingClientRect().top;
}
}
它已被记录,但除非我调整窗口大小,否则该方法的其余部分不起作用
奇怪的行为和可能有用的数据:
我在项目中有一个中等复杂的组件结构,我必须将它应用到两个不同的组件上,奇怪的是我在一个组件上完美地工作,但在另一个组件上却不行,这种情况是它不起作用的组件正在呈现在已经在另一个路由器视图中的路由器视图中(它是子路由),该组件具有以下结构:
<Root>
<App>
<Navbar>
<News> router-view: /news <-- HERE IT WORKS
<Root>
<App>
<Navbar>
<League> router-view: /league
<Statistics> router-view /league/statistics <-- HERE IT DOESN'T
如果您需要更多信息,请告诉我
【问题讨论】:
标签: javascript events vue.js scroll