【发布时间】:2019-06-02 12:34:55
【问题描述】:
使用 Quasar 框架我有多个孩子,需要在加载页面后滚动到某个孩子。我可以通过使用 setTimeout 设置延迟来做到这一点,但我更喜欢更好/防故障的解决方案。
我目前的方法是等待所有孩子安装(并使用nextTick)并认为它应该准备好滚动,但显然不是。或者,我可以等待所有图像被加载(因为QImg 有一个@load event),但这已经很晚了,因为当图像框已经渲染但仍在加载时,我已经可以手动触发滚动了。
“尽早”触发的最佳方式是什么?
点面板(父级):
new Vue({
el: '#q-app',
template: `
<div id="point-panel" class="map-overlay column scroll">
<small-cards
@hook:mounted="cardsAreReady(cardIndex, picArray.length)"
v-for="(point, cardIndex) in picArray"
:key="cardIndex"
:point-object="point"
:card-index="cardIndex"
/>
<q-btn
@click.native="scrollToCenter"
fab
ripple
class="fixed"
size="10px"
color="black"
label="scroll"
style="right: 18px; bottom: 120px"
/>
</div>
`,
data: function () {
return {
selectedPointIndex: 6,
picArray: ['https://image1', 'https://image2', 'https://image_etc.']
}
},
methods: {
notify (msg) {
this.$q.notify(msg)
},
cardsAreReady (cardIndex, total) {
console.log('one ready.......', `${cardIndex} ...and total ${total}`)
const that = this
if (cardIndex + 1 === total) {
console.log('....all cards MOUNTED!', cardIndex)
setTimeout(() => {
that.$nextTick(() => {
console.log('..........trigger scroll NOW!')
that.scrollToCenter()
})
}, 0)
}
},
scrollToCenter () {
const that = this
console.log('..........cardIndex: ', that.selectedPointIndex)
that.notify('scroll triggered!')
function scrollFunction () {
const element = document.getElementsByClassName(
that.selectedPointIndex.toString()
)
const target = document.getElementById('point-panel')
const iW = window.innerWidth
const iH = window.innerHeight
const myOffset = element[0].offsetLeft
Quasar.utils.scroll.setHorizontalScrollPosition(target, myOffset, 0)
}
setTimeout(() => scrollFunction(), 0)
}
}
})
图片/小卡片(儿童):
Vue.component('small-cards', {
props: {
pointObject: {
type: Object,
required: true
},
cardIndex: {
type: Number,
required: true,
default: 0
}
},
data: function () {
return {
selectedPointIndex: 6
}
},
methods: {
reportError (event) {
console.log(`${event.name}: ${event.message}`)
},
},
template: `
<div
class="mycard"
:class="{
'active': cardIndex === selectedPointIndex,
[cardIndex]: true
}"
>
<q-img
:src="pointObject"
spinner-size="30px"
style="background-color: rgba(255, 225, 215, 0.4)"
@error="reportError"
/>
</div>
`
})
在这里您可以找到显示问题的jsfiddle。我添加了一个滚动按钮,显示加载后可以成功触发滚动(第6张图片,即“老虎”滚动到左下角)。
编辑:给这个问题更多的方向:问题是如果scroll 很快被触发,DOM 还没有渲染,因此滚动的距离还不能确定。但我会认为之后
mount Dom 应该确定了吧?!那么为什么当前的方法不起作用呢?
【问题讨论】:
标签: javascript vue.js quasar-framework