vue使用better-scroll导航滚动的指定位置

思路:

  • 主要是通过better-scroll的scrollToElement()方法来实现的
import BScroll from 'better-scroll';

template:

        <div class="tab" ref="tab">
            <ul ref="tabWrapper" class="ultab">
                <li :class="{red: item.id === active}" v-for="item in tabList" :key="item.id" @click="clickTab(item.id)" ref="tabitem">
                    <span>{{item.name}}</span>
                </li>
            </ul>
        </div>

data

            tabList: [{
                    id: '',
                    name: "全部"
                },
                {
                    id: 0,
                    name: "待接单"
                },
                {
                    id: 1,
                    name: "待发货"
                },
                {
                    id: 2,
                    name: "待收货"
                },
                {
                    id: 3,
                    name: "已完成"
                },
                {
                    id: 4,
                    name: "已取消"
                },
            ],

mounted:

            this.$nextTick(() => {
                this.InitTabScroll();
                let a = document.querySelector(".ultab .red")
                console.log(a);
                this.scroll.scrollToElement(a, 0, 0)
            });

methods:

InitTabScroll() {
                let width = 0
                for (let i = 0; i < this.tabList.length; i++) {
                    width += this.$refs.tabitem[0].getBoundingClientRect().width; //getBoundingClientRect() 返回元素的大小及其相对于视口的位置
                }
                this.$refs.tabWrapper.style.width = width + 'px';
                this.scroll = new BScroll(this.$refs.tab, {
                    startX: 0,
                    click: true,
                    scrollX: true,
                    scrollY: false,
                    bounce: false,
                    eventPassthrough: 'vertical'
                });
            },

猜你喜欢

转载自blog.csdn.net/qq719756146/article/details/85004309