1. 程式人生 > >vue-music 關於Search(搜索頁面)-- 搜索結果優化

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

function 如果 RR fin pan 包含 開始 一次 con

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

在suggest.vue 組件判斷如果點擊的是歌手,則new 一個歌手對象,通過這個對象的id 屬性值傳遞給路由的參數,通過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 播放列表

點擊添加一首歌需要更改操作三個狀態,在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 毫秒去監聽請求,減少發無效的請求

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 失去焦點

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

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

// 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();
}

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