better-scroll跳转到指定元素位置
安装插件
npm i better-scroll --save
在需要使用的文件里面导入
import BScroll from 'better-scroll'
符合插件使用的条件结构
<div class="wrapper" ref="wrapper"> // 一个包装
<ul class="content"> // 一大块内容
<li>...</li> // 具体内容
<li>...</li>
...
</ul>
</div>
具体代码实现
<template>
<!-- 包装 -->
<div class="wrapper" ref="wrapper">
<div>
<!-- 内容 -->
<div class="content" :ref="index" v-for="index in 10" :key="index">
{{ index }}
</div>
</div>
<!-- 右边数字列 -->
<!-- 注意: 右边的数字列要放在内容div后,否则position: fixed;不生效 -->
<ul class="alphabet">
<li v-for="index in 10" :key="index + '1'" @click="handleClick">
{{ index }}
</li>
</ul>
</div>
</template>
<script>
// 引入BScroll
import BScroll from "better-scroll";
export default {
data() {
return {
letter: "",
};
},
mounted() {
// 初始化better-scroll
this.scroll = new BScroll(this.$refs.wrapper);
},
methods: {
handleClick(e) {
// 获取点击的数字
this.letter = e.target.innerText;
console.log(e.target.innerText, "点击的数字");
},
},
// 监听letter的变化,执行操作
watch: {
letter() {
// 跳转到对应数字的div区域
this.scroll.scrollToElement(this.$refs[this.letter][0]);
console.log(this.$refs[this.letter][0]);
},
},
};
</script>
<style>
.wrapper {
position: absolute;
overflow: hidden;
width: 100%;
height: 100%;
background: rgb(77, 156, 40);
}
.content {
height: 200px;
width: 100px;
font-size: 20px;
background: rgb(13, 143, 34);
}
.alphabet {
position: fixed;
right: 0;
top: 1rem;
bottom: 0;
text-align: center;
font-size: 50px;
font-weight: bold;
/* background: rgb(55, 150, 153); */
}
</style>
效果演示
第一次写文章,忐忑发布,希望对你们有帮助吧![狗头.jpg]