使用elementUI组件el-select实现音乐搜索
<template>
<div>
//文档地址 https://element.eleme.cn/#/zh-CN/component/select
<el-select class="pt-1 pb-1 pr-2" style="width:150px" v-model="value" filterable="true" remote="true" reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading" >
<el-option v-for="item in options" :key="item.id" :value="item.name">
</el-option>
</el-select>
//路由跳转
<router-link @click.native="flushCom" :to="{ path: 'searchList', query: { text: this.value } }" >
<el-button v-if="this.value.length" icon="el-icon-search" circle ></el-button ></router-link>
</div>
</template>
<script> export default { data() { return { options: [], value: [], loading: false }; }, mounted() {}, methods: { remoteMethod(query) { //从接口获取模糊查询后的结果 if (query !== "") { this.$http .get("/search", { params: { keywords: query.trim() } }) .then(res => { this.options = res.data.result.songs; }); } else { this.options = []; } }, flushCom: function() { //router.go(n)是路由的一个方法,意思是在history记录中前进或者后退多少步,0就表示还是当前,类似 window.history.go(n) this.$router.go(0); } } }; </script>
当输入框为空时,默认是不显示搜索按钮的,我们选中一个搜索结果,按钮就会出现
这时页面跳转到搜索结果页面
<template>
<div class="pl-3 pr-4">
<table class="table table-condensed">
<tr border="1px" v-for="(item, index) in list" :key="index">
<th>
<hr />
<span>
<div>{{ item.name }}</div></span >
</th>
<th>
<hr />
<span v-for="elem in item.artists" :key="elem">
<font size="2rem" color="grey">{{ elem.name }}</font>
</span>
</th>
<th>
<div class="pt-5">
<i @click="audio(item.id)" class="el-icon-video-play"></i>
</div>
</th>
</tr>
</table>
</div>
</template>
<script> export default { data() { return { list: [] }; }, created() { this.fetch(); }, methods: { async fetch() { await this.$http .get("/search", { params: { keywords: this.$route.query.text, limit: 15 } }) .then(res => { this.list = res.data.result.songs; }); }, async audio(id) { let curMusic; await this.$http .get("/song/detail", { params: { ids: id } }) .then(res => { //将歌曲加入队列并且开始播放 curMusic = { pic: res.data.songs[0].al.picUrl, title: res.data.songs[0].name, artist: res.data.songs[0].ar[0].name, src: this.$store.state.MusicUrl + id + ".mp3", lrc: "" }; }); const res = await this.$http.get("/lyric?id=" + id); curMusic.lrc = res.data.lrc.lyric; await this.$store.commit("addMusic", curMusic); } } }; </script>