vue-搜索功能-实时监听搜索框的输入,N毫秒请求一次数据
<template> <div class="search-box"> <input class="box" :placeholder="placeholder" v-model="query" > </div> </template> <script type="text/ecmascript-6"> import { debounce } from 'common/js/util' export default { props: { placeholder: { type: String, default: '搜索歌曲、歌手' } }, data() { return { query: '' } }, created() { this.$watch('query', debounce((newQuery) => { this.$emit('query', newQuery) }, 200)) } } </script>
export function debounce(func, delay) { let timer; return function (...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, delay) } }