移動端經常會用頁面高度超過了手機屏幕的高度,但是有沒有滾動條的出現這時候就用 better-scroll 這個插件, iscroll 是常用的但是這個組件沒有人在維護了,導致很多的問題沒有辦法解決。
better scroll 的頁面結構為
<div class="shop_box" ref="shopBox"> <div class="shop_container"> <div class="shop_header"> </div> </div> </div> 第一層 div: 高度固定比如是手機屏幕的高度,overflow-y:hidden; 第二層 div: 高度不固定,只設置寬度 100%。 第三層 div: 數據部分,肯能有很多很多
1、vue2 中如何使用 better-scroll
首先安裝better-scroll,然后在配置文件中查看
"dependencies": { "vue": "^2.2.6", "vue-router": "^2.3.1", "vue-resource": "^1.3.3", "better-scroll": "^0.1.7" },
然后在要用的地方引用這個組件
import BScroll from 'better-scroll';
接下來初始化這個組件,在methods 里面將這個寫為一個方法
_initScroll () { this.shopBoxScroll = new BScroll(this.$refs.shopBox, { // better-scroll 會將點擊事件去掉,要在這里開啟,同時點擊在PC 會被執行兩次,要在這里控制 click: true }); }
然后在函數鈎子里面調用這個方法,因為mvvm 框架的數據是一步的所以要在函數周期里面使用
created () { this.$nextTick(() => { this._initScroll(); }); },
在頁面中要調用的地方
<div class="shop_box" ref="shopBox">
整體為:
<script> import starT from '../star/star.vue'; import BScroll from 'better-scroll'; export default { props: { seller: { type: Object } }, created () { this.$nextTick(() => { this._initScroll(); }); this.classMap = ['min', 'discount', 'guarantee', 'invoice', 'special']; }, methods: { _initScroll () { this.shopBoxScroll = new BScroll(this.$refs.shopBox, { // better-scroll 會將點擊事件去掉,要在這里開啟,同時點擊在PC 會被執行兩次,要在這里控制 click: true }); } }, components: { 'v-star': starT } }; </script>
(總結):1、在 vue2中如何獲取dom 結構
在要獲取的dom元素上添加
ref="shopBox"
這樣在 js 中
$refs.shopBox便可以獲取dom 元素。
有時候經常匯報better-scroll 找不到孩子元素原因是:
html 中 ref="" 中間不要用空格盡量用駝峰命名
2、移動端經常會有這種場景

數據是橫行滾動的,這個時候也是better-scroll 只不過這回改成橫向滾動的就行
this.picScroll = new BScroll(this.$refs.pic_scroll, { // better-scroll 會將點擊事件去掉,要在這里開啟,同時點擊在PC 會被執行兩次,要在這里控制 click: true, scrollX: true, eventPassthrough: 'vertical' });
3、動態DOM使用 better-scroll
在vue 中如果使用 v-show 控制一個dom的顯示隱藏並且這個 dom 中要有 better-scroll 的效果,在v-show 控制顯示的地方調用初始化better-scroll的函數便可以,
但是一定要放到this.$nextTick 里面,因為 vue 中 dom都是異步加載。
// 篩選 chooseScreenShop () { // tab 高兩 this.screenTabtHight = !this.screenTabtHight; // 去除其它高亮顯示 this.classification = false; this.sortHightLight = false; // 篩選 if (this.screenTabtHight === true) { this.screenShopList = true; this.$nextTick(() => { this._init(); }); // 其他的隱藏 this.sortShopList = false; this.classificationBox = false; } else { this.screenShopList = false; } this.dailog(); },
better-scroll 官網地址為:https://www.npmjs.com/package/better-scroll
在這里面有詳細的解說