通用組件的設計原則:解耦vue
props: { placeholder: { type: String, default: '搜索歌曲、歌手' } },
created() { //優化:添加節流函數 this.$watch('query', _debounce((newQuery) => { this.$emit('query', newQuery) }, 300)) },
開始滾動的時候在移動端輸入框的鍵盤收縮
,由父組件search.vue中開始滾動派發的事件,調用該方法,參考圖片app
blur() { this.$refs.query.blur() }
首先滾動至底部派發事件在scroll.vue組件中
這裏是經過props,若是須要傳值,則派發滾動至底部事件
僞代碼:dom
//滾動開始派發事件 beforeScroll: { type: Boolean, default: false } .... _initScroll() { this.scroll = new BScroll(this.$refs.wrapper, { probeType: this.probeType, click: this.click }) //上拉刷新,滾動到底部派發一個事件 if (this.pullup) { this.scroll.on('scrollEnd', () => { if (this.scroll.y <= (this.scroll.maxScrollY + 50)) { this.$emit('scrollToEnd') } }) } }
在suggest.vue中接收派發事件函數
hasMore
標誌位進行判斷,是否能夠加載更多page
標記頁碼
searchMore() { //當沒有的時候中止加載 if (!this.hasMore) { return } //頁碼page更改 this.page++ search(this.query, this.page, this.showSinger, perpage).then((res) => { if (res.code === ERR_OK) { //concat拼接 this.result = this.result.concat(this._genResult(res.data)) this._checkMore(res.data) } }) }, /** * 上拉刷新,是否還有數據 */ _checkMore(data) { const song = data.song //若是沒有song或者 加載的數量 > if (!song.list.length || (song.curnum + song.curpage * perpage) >= song.totalnum) { this.hasMore = false } }, search() { //下次搜索的時候初始化 this.page = 1 this.$refs.suggest.scrollTo(0, 0) this.hasMore = true //search是請求接口數據方法 search(this.query, this.page, this.showSinger, perpage).then((res) => { if (res.code === ERR_OK) { this.result = this._genResult(res.data) this._checkMore(res.data) } }) },
滾動scroll.vue組件包含兩部分數據:hotKey searchHistory,兩部分數據須要經過計算屬性computed組合concat起來,而後傳入scroll.vue組件:data中
優化
當query從有到無的時候,下面的dom結構display發生了改變,一次須要scroll刷新this
<div ref="shortCutWrapper" class="shortcut-wrapper" v-show="!query"> <scroll ref="scroll" class="shortcut" :data="shortcut"> </div>
在watch中,刷新scrollspa
watch: { query(newQuery) { if (!newQuery) { setTimeout(() => { this.$refs.scroll.refresh() }, 20) } } },