前端实现搜索联想时防抖功能:
生活随笔
收集整理的這篇文章主要介紹了
前端实现搜索联想时防抖功能:
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.原因:
在輸入搜索文本時,會不停的調用接口,消耗大量性能=>引入js中Loadsh工具類來解決Loadsh工具官網
2.案例使用:
[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>總結
以上是生活随笔為你收集整理的前端实现搜索联想时防抖功能:的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SringBoot实现PDF签字盖章
- 下一篇: VSCode插件,TODO标记