vue-music 關於Search(搜索頁面)-- 搜索結果優化

搜索結果 列表點擊跳轉到相應的歌手詳情頁或者 歌曲頁面,經過子路由跳轉,和singer 組件同樣vue

在suggest.vue 組件判斷若是點擊的是歌手,則new 一個歌手對象,經過這個對象的id 屬性值傳遞給路由的參數,經過vuex 傳遞歌手數據vuex

<li class="suggest-item" v-for="item in result" @click="selectItem(item)">

selectItem(item){
  if(item.type === TYPE_SINGER){
    let singer = new Singer({
      id:item.singermid,
      name:item.singername
    })
    this.$router.push({
      path:`/search/${singer.id}`
    })
    this.setSinger(singer)
  }else{
    ...//歌曲點擊邏輯
  }
},

歌曲點擊的邏輯和以前選擇歌手點擊列表邏輯不一樣,以前是改變全部的playlist 列表,而搜索出來的列表點擊 只須要向當前playlist 列表添加一首便可,不須要改變整個playlist 播放列表app

點擊添加一首歌須要更改操做三個狀態,在actives.js 中寫相關commit insetSong 函數 插入一首搜索結果的歌曲,而後判斷與原來的播放列表中是否有這首歌曲,若是有則刪除,更新playlist 和 sequenceList 列表函數

export const insertSong = function ({commit,state},song){
  let playlist = state.playlist.slice();
  let sequenceList = state.sequenceList.slice();
  let currentIndex = state.currentIndex;

  //記錄當前歌曲
  let currentSong = playlist[currentIndex];
  // 查找當前列表中是否有待插入的歌曲並返回其索引
  let fpIndex = findIndex(playlist, song)
  // 由於是插入歌曲,因此索引+1
  currentIndex++
  // 插入這首歌到當前索引位置
  playlist.splice(currentIndex, 0, song)
  // 若是已經包含了這首歌
  if (fpIndex > -1) {
    // 若是當前插入的序號大於列表中的序號
    if (currentIndex > fpIndex) {
      playlist.splice(fpIndex, 1)
      currentIndex--
    } else {
      playlist.splice(fpIndex + 1, 1)
    }
  }

  let currentSIndex = findIndex(sequenceList, currentSong) + 1
  let fsIndex = findIndex(sequenceList, song)
  sequenceList.splice(currentSIndex, 0, song)
  if (fsIndex > -1) {
    if (currentSIndex > fsIndex) {
      sequenceList.splice(fsIndex, 1)
    } else {
      sequenceList.splice(fsIndex + 1, 1)
    }
  }
  commit(types.SET_PLAYLIST, playlist)
  commit(types.SET_SEQUENCE_LIST, sequenceList)
  commit(types.SET_CURRENT_INDEX, currentIndex)
  commit(types.SET_FULL_SCREEN, true)
  commit(types.SET_PLAYING_STATE, true)
}

邊界處理。若是搜索無結果,顯示no-result 組件,當前搜索輸入框每一次輸入時都會監聽query 變化去請求,從源頭作節流函數延時200 毫秒去監聽請求,減小發無效的請求this

export function debounce(func, delay) {        //函數科裏化
  let timer

  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}
import {debounce} from 'common/js/util.js'

created(){
  this.$watch('query',debounce((newQuery) => {
    this.$emit('query',newQuery);
  },200))
},

在手機端當搜索完成滾動搜索列表時,底部的軟鍵盤會當住滾動列表,要作的就是在監聽scroll 滾動的時候讓input 失去焦點spa

首先在scroll 上新增beforeScroll事件 監聽beforeScrollStart 滾動開始事件,去派發一個事件。而後在搜索結果列表監聽派發事件,再次派發給search 組件code

在searchbox 組件裏給input 設置失去焦點 blur 函數。search組件中監聽搜索列表 派發事件 調用 this.$refs.searchBox.blur(); 設置失焦router

// scroll.vue

if(this.beforeScroll){
  this.scroll.on('beforeScrollStart',()=>{
    this.$emit('beforeScroll')
  })
}


// search-box.vue

blur(){
  this.$refs.query.blur();
  console.log("失焦")
}


//search.vue

blurInput(){
  this.$refs.searchBox.blur();
}
相關文章
相關標籤/搜索