在输入搜索文本时,会不停的调用接口,消耗大量性能=>引入js中Loadsh工具类来解决
[1]安装依赖
npm i --save lodash
[2]引入使用
<script>
import { debounce } from 'lodash' //js工具类,按需加载
export default {
name: 'SearchSuggestion',
props: {
searchText: {
type: String,
required: true
}
},
data() {
return {
suggestionsList: [],
}
},
watch: {
searchText: {
// 当searchText发生改变,调用handler函数(名称固定)
// handler(value) {
// this.getSearchSuggestionsList(value)
// },
/*
优化防抖
debounce函数:
参数一:一个函数
参数二:延迟时间,单位毫秒
返回值:防抖之后的函数
*/
handler: debounce(function (value) {
this.getSearchSuggestionsList(value)
}, 1000),
immediate: true, //侦听之后立即被调用
}
},
created() {
},
methods: {
// 获取联想推荐列表
async getSearchSuggestionsList(value) {
try {
// const {res}=await getSearchSuggestions(value)
this.suggestionsList = [
{ content: '1', url: 'https://www.baidu.com/?tn=02003390_25_hao_pg' },
{ content: '2', url: 'https://www.baidu.com/?tn=02003390_25_hao_pg' },
{ content: '3', url: 'https://www.baidu.com/?tn=02003390_25_hao_pg' },
{ content: '4', url: 'https://www.baidu.com/?tn=02003390_25_hao_pg' },
{ content: '5', url: 'https://www.baidu.com/?tn=02003390_25_hao_pg' },
]
console.log(value)
} catch (error) {
this.$toast('数据获取失败,请稍后重试')
}
},
}
}
</script>