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);
    },

原文地址:https://www.cnblogs.com/Small-Windmill/p/14952394.html