scroll-view コンポーネントには、scroll-into-view 属性があります: (値は子要素 ID である必要があります。スクロール可能な方向を設定してから、どの方向の要素までスクロールします)。[公式スクロールビュー説明]
この属性の意味は、この属性の値が子要素で設定したidの場合、子要素の位置にジャンプできるということです。
まず効果を確認します。
コードを直接アップロードします:
html:
<template>
<view>
<scroll-view scroll-y="true" :scroll-into-view="intoView" :style="`height: 200px`" scroll-with-animation="true">
<view class="item" v-for="(item, index) in arr" :key="index" :id='"text" + (index+1)'>{
{ item }}</view>
</scroll-view>
<button @tap="move(1)">点击移动至1</button>
<button @tap="move(2)">点击移动至2</button>
<button @tap="move(3)">点击移动至3</button>
<button @tap="move(4)">点击移动至4</button>
<button @tap="move(5)">点击移动至5</button>
<button @tap="move(6)">点击移动至6</button>
</view>
</template>
js:
<script>
export default {
data() {
return {
arr: [1,2,3,4,5,6],
intoView: ''
}
},
methods: {
move(num) {
this.$nextTick(()=> {
this.intoView = "text" + num
console.log(this.intoView)
})
}
}
}
</script>
[注意] なお、scroll-viewの高さは必ず設定する必要があり、未設定の場合は効果がありませんが、親要素に高さを記述していない場合は100%に設定しないでください。