搜索功能的实现

搜索

1.新建总页面views / Search.vue

2.在 router/ index.js中联系Search.vue 与 App.vue

3.在 topNav.vue 中给搜索图标添加点击连接,跳转到Search搜索页面

<div class="topRight" @click="$router.push('/Search')">

分块配置搜索页面

顶部:

1.新建components / searchTop.vue

2.联系searchTop.vue与 Search.vue

 <div id="searchPage"><searchTop></searchTop></div>

在Search.vue 中引入配置searchTop.vue

3.配置searchTop.vue页面

//1.给返回图加点击返回事件
<svg class="icon" aria-hidden="true" @click="$router.push('/')">

输入框:

<input type="text" v-model="searchKeyword" placeholder="张艺兴">

export default中:

data(){  
  return{        searchKeyword:"" //用户输入需要搜索的内容    
}}

 

列表:

1.封装搜索歌曲的api接口

//搜索歌曲 api
//  /search?keywords=海阔天空`  keywords:当前要搜索的数据
export function searchMusic(keywords) {
    return axios(`${baseUrl}/search?keywords=${keywords}`)
}

添加键盘回车事件

<input type="text" v-model="searchKeyword" placeholder="张艺兴" @keydown.enter="searchSong">

回车绑定事件 searchSong 函数

methods: {
    async searchSong() {
        //回车绑定事件
        console.log('用户要搜索' + this.searchKeyword)
        let res=await searchMusic(this.searchKeyword)
        console.log(res)
        this.searchSongs=res.data.result.songs
    }
},

引入

import {searchMusic} from "@/api/index.js";

 

后台接收并搜索:

data 中设置接收搜索到的歌曲列表 searchSongs

data() {    return {     
   searchKeyword: "", //用户输入需要搜索的内容     
   searchSongs: []    //接收搜索到的歌曲列表  
  }}

将接口内容放到搜索到的歌曲列表 searchSongs 中

async mounted() {    let res = await searchMusic();    //console.log(res)    this.searchSongs = res.data.result.songs    //console.log(res.data.result.songs)}

template中配置 循环

<div class="list" v-for="(item,i) in searchSongs" :key="i">
    <div class="playItem">
        <div class="left">
            <div class="index">{{i+1}}</div>
            <div class="content">
                <div class="title">{{item.name}}</div>
                <div class="anther">
                    <div class="num">{{item.album.name}}</div>
                </div>
            </div>
        </div>

 

播放搜索到的歌曲

1.在store / index mutations中

定义一个函数,搜索歌曲点击切换时,将点击的这首歌曲添加到state的播放列表末尾

 

pushPlayList(state,value){   
    state.playlist.push(value)   //push()在数组末尾追加内容
},

 

2.在searchTop.vue 中

给播放图标添加click事件, 设置触发setPlay函数

 

<svg class="icon" aria-hidden="true" @click="setPlay(item)">

在 mathods 中添加 setPlay 函数

 

setPlay(item) {
    console.log('当前要播放的歌曲' + item)  //当前要播放的歌曲
    item.al = item.album //搜索歌曲数据与之前数据列表格式不同,要转换格式
    item.al.picUrl = item.album.artist.img1v1Url
    
 法1:直接调用法:
    // this.$store.commit('pushPlayList', item)
     //触发store中的方法,将点击歌曲追加至歌曲列表末尾
    // this.$store.commit('setPlayIndex',        this.$store.state.playlist.length - 1)
    
法2: mapMutations法
    this.pushPlayList(item)
    this.setPlayIndex(this.playlist.length-1)
},
...mapMutations(['pushPlayList', "setPlayIndex"])

法2:

并引入和加入

import {mapState, mapMutations} from 'vuex'
computed: {    ...mapState(['playlist'])},

 

posted @ 2022-05-12 14:18  絮行  阅读(283)  评论(0编辑  收藏  举报