在scroll-view組件中有一個scroll-into-view屬性:(值應為某子元素id。設置哪個方向可滾動,則在哪個方向滾動到該元素)。【官方scroll-view說明】
此屬性的意思則是此屬性的值為子元素設置的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%,除非父元素寫了高度。