欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue2中引用及使用 better-scroll的方法详解

程序员文章站 2022-11-23 12:16:22
使用时有三个要点: 一:html部分
...

使用时有三个要点:

一:html部分

<div class="example" ref="divscroll">
  <div>
    <p>内容1</p>
    <p>内容2</p>
    <ul>
       <li>list1</li>
       <li>list2</li>
    <ul>
  </div>
</div>

【注】

1.最外层加ref,让better-scroll通过ref来获取整个div;

 2.紧跟一个div,不用加任何样式或class, 最终可以滑动的部分就是这个div,这个div必须是 加了ref 的div 的 直接子元素。  在这个div里面就可以放置希望滑动的内容了。

二: css部分

.example
 width: 100%
 position: absolute
 top: 174px
 bottom: 48px
 left: 0
 overflow: hidden

【注】 1. 这里只是举例,并不是一定要这样写。

    2. 首先将 获取到的加了 ref 的div 的 高度固定, 可以设置定位, 也可以设置  height, max-height...

    3. 加 overflow: hidden 。

三: js 部分

首先 引入 better-scroll:

import bscroll from 'better-scroll';

1: 使用 mounted() 函数

mounted() {
  this.scroll = new bscroll(this.$refs.divscroll, {
    click: true,
  });
 },  

2.使用 created() 函数

created() {
  this.$nexttick(() => {
   this.scroll = new bscroll(this.$refs.divscroll, {
    click: true,
   });
  });
},

【注】 1.使用created 函数 要异步执行(此时html 尚未渲染完成)。

    2. mounted函数 无需异步执行(mounted 函数在html渲染完成后触发)。

下面看下vue中引入better-scroll的方法

1.用npm 安装好 better-scroll

npm install--save better-scroll

2.在需要的页面引入

import bscroll from 'better-scroll'

3.在data中定义 better-scroll的参数

options: {
     pulldownrefresh: {
      threshold: 50, // 当下拉到超过顶部 50px 时,触发 pullingdown 事件
      stop: 20 // 刷新数据的过程中,回弹停留在距离顶部还有 20px 的位置
     },
     pullupload: {
      threshold: -20 // 在上拉到超过底部 20px 时,触发 pullingup 事件
     },
//     pulldownrefresh: false, //关闭下拉
//     pullupload: false, // 关闭上拉
     click: true,
     probetype: 3,
     starty: 0,
     scrollbar: true
    }

4.在template中写入

<div class="wrapper" ref="wrapper" :scrollbar="options.scrollbar" :starty="options.starty">

5.在methods中写入方法,我自定义的

load() {
    if (!this.scroll) {
     this.scroll = new bscroll(this.$refs.wrapper, this.options);
     // 上拉
     this.scroll.on('pullingup', () => {
      // 刷新数据的过程中,回弹停留在距离顶部还有20px的位置
      this.setdata();
     })
    } else {
     this.scroll.refresh()
    }
   },
 setdata() {
    this.$nexttick(() => {
     let arr = [1, 2, 3, 'james'];
     this.data = this.data.concat(arr)// 添加数据
     this.scroll.finishpullup();
     this.pullingdownup()
    })
   },
pullingdownup() {
    this.scroll.refresh() //重新计算元素高度
   },

6.在created中加载

 this.$nexttick(() => {
    this.load()
    this.setdata()
   })

总结

以上所述是小编给大家介绍的vue2中引用及使用 better-scroll的方法详解,希望对大家有所帮助