前言
better-scroll官方demo展示:https://ustbhuangyi.github.io/better-scroll/#/examples/en
better-scroll官方文檔說明:https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/#better-scroll
方法一:官方文檔推薦的方法
<template> <div class="wrapper"> <ul class="content"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div> </template> <script> import BScroll from 'better-scroll' export default { name: 'CityList', mounted () { this.scroll = new BScroll('.wrapper') } }
注:① 上面代碼中better-scroll是作用在外層 wrapper 容器上的,必須有這個父容器包裹,
滾動部分是子元素content ,也就是滾動的內容
② better-scroll只處理父容器wrapper的第一個子元素content的滾動,其它的元素都會被忽略
比如你在上面的<ul class="content"></ul>后面在添加一個同級<ul class="content2"></ul>,
被.content2包裹的內容是不會滾動的
方法二:用vue的ref屬性獲取wrapper節點
<template> <div class="main" ref="wrapper"> <ul class="content"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div> </template> <script> import BScroll from 'better-scroll' export default { name: 'CityList', mounted () { this.scroll = new BScroll(this.$refs.wrapper) } }
注: ① ref的作用是給元素或子組件注冊引用信息,引用信息將會注冊在父組件的$refs
對象上
如果在普通的DOM元素上使用,引用指向的就是DOM元素;如果用在子組件上,引用就指向組件
上面的代碼中,ref指的就是DOM元素.wrapper
② this.$refs.wrapper就是獲取到DOM元素.wrapper