1. 程式人生 > 其它 >VUE移動端音樂APP學習【二十一】:熱門搜尋開發

VUE移動端音樂APP學習【二十一】:熱門搜尋開發

通過api獲取熱門搜尋關鍵詞

  • 設定api
//search.js
import axios from 'axios';

export function getHotKey() {
  return axios.get('/api/search/hot');
}
  • 在search.vue中使用api獲取資料
import { getHotKey } from '../../api/search';
import { ERR_OK } from '../../api/config';

 created() {
    this._getHotKey();
  },
  methods: {
    _getHotKey() {
      getHotKey().then((res) 
=> { if (res.data.code === ERR_OK) { console.log(res.data.result.hots); } }); }, },
  • 將資料定義到data上,然後進行遍歷
    <div class="shortcut-wrapper">
      <div class="shortcut">
        <div class="hot-key">
          <h1 class="title">熱門搜尋</
h1> <ul> <li class="item" v-for="(item,index) in hotKey" :key="index"> <span>{{item.first}}</span> </li> </ul> </div> </div> </div> data() { return { hotKey: [], }; }, methods: { _getHotKey() { getHotKey().then((res) => { if (res.data.code === ERR_OK) { this.hotKey = res.data.result.hots; } }); }, },

接下來實現點選熱門搜尋詞就自動填充到搜尋框中的功能

  • 給列表上的元素繫結點選事件
<li @click="addQuery(item.first)" class="item" v-for="(item,index) in hotKey" :key="index">
  • 給search-box.vue新增一個介面方法
    setQuery(Query) {
      this.query = Query;
    },
  • 在父元件search.vue中呼叫該介面
<div class="search">
    <div class="search-box-wrapper">
      <search-box ref="searchBox"></search-box>
 </div>

addQuery(Query) {
      this.$refs.searchBox.setQuery(Query);
    },