vue_music:搜索search.vue

1. 經典搜索框search-box.vue

clipboard.png
通用組件的設計原則:解耦vue

1. 經過props,傳遞placeholder信息

props: {
    placeholder: {
      type: String,
      default: '搜索歌曲、歌手'
    }
  },

2. 派發輸入框中的輸入值query

created() {
    //優化:添加節流函數
    this.$watch('query', _debounce((newQuery) => {
      this.$emit('query', newQuery)
    }, 300))
  },

3. 移動端收起鍵盤

開始滾動的時候在移動端輸入框的鍵盤收縮,由父組件search.vue中開始滾動派發的事件,調用該方法,參考圖片app

blur() {
  this.$refs.query.blur()
}

2. 搜索框下拉加載更多

clipboard.png

1. 滾動至底部派發事件

首先滾動至底部派發事件在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')
      }
    })
  }
}

2.接收派發事件

在suggest.vue中接收派發事件函數

  • hasMore標誌位進行判斷,是否能夠加載更多
  • page標記頁碼

clipboard.png

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)
    }
  })
},

3. 搜索狀態優化

  • 加載狀態:loading組件
  • 搜索結果: no-result組件

clipboard.png

4. 滾動

滾動scroll.vue組件包含兩部分數據:hotKey searchHistory,兩部分數據須要經過計算屬性computed組合concat起來,而後傳入scroll.vue組件:data中
clipboard.png優化

5.優化

1. query變化

當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)
      }
    }
},
相關文章
相關標籤/搜索