gpt4 book ai didi

javascript - 在 Vuetify 自动完成搜索中通过 API 进行搜索非常慢

转载 作者:行者123 更新时间:2023-12-02 21:32:05 25 4
gpt4 key购买 nike

我正在使用 Vuetify 自动完成组件来搜索所有股票代码和公司名称(总共 117230 个)。当我输入搜索词时,浏览器会变得非常滞后几秒钟。当我用很少的记录(6000)尝试时,没有问题。该 API 目前在本地托管。

我假设这项工作应该由后端完成?但我不知道怎么做。我有什么选择?

搜索组件中的Javascript代码:

import Chart from './GChart.vue'
export default {
name: "Search",
components: {
Chart,
},
data: () => ({
symbolsExchangesNames: [],
isLoading: false,
model: null,
search: null
}),

computed: {
items () {
return this.symbolsExchangesNames
}
},

watch: {
search (val) {
console.log(val)
if (this.items.length > 0) return
if (this.isLoading) return
this.isLoading = true
fetch('http://localhost/API/allSymbolsExchangesNames')
.then(res => res.json())
.then(res => {
for(let i of res){
this.symbolsExchangesNames.push({
Code: i.Symbol,
Exchange: i.Exchange,
Name: i.Name,
CodeAndName: `${i.Symbol} ${i.Name}`
})
}
})
.catch(err => {
console.log(err)
})
.finally(() => (this.isLoading = false))
}
}
}

数据如下:

[{"Symbol": "A", "Exchange": "US", "Name": "Agilent Technologies, Inc"}, {"Symbol": "AA", "Exchange": "US", "Name": "Alcoa Corporation"},...]

最佳答案

117k 条记录需要一些时间才能以 HTML 形式呈现。

我建议您使用一些 debounce 函数(在下面的示例中我使用 underscore ),仅在用户停止输入时查询您的后端,或者您可以使用某种真实类型的输入,例如在输入中按 Enter 键或提交表单。

并且您应该防止后端返回如此多的记录,所以是的,您应该在后端过滤结果,通常在 GET 请求上使用查询字符串( https://www.google.com/search?q=text%20to%20search )

new Vue({
el: "#app",
data() {
return {
query: "",
data: []
}
},
methods: {
// with debounce, 300ms after user stops typing, the callback will be executed
search: _.debounce(function() {
// here you should query your backend, something like
// http://localhost/API/allSymbolsExchangesNames?query=#{this.query}
this.data = [1,2,3]
}, 300)

}
})
<script src="https://underscorejs.org/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<input v-model="query" @keypress="search" />
{{data}}
</div>

关于javascript - 在 Vuetify 自动完成搜索中通过 API 进行搜索非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60597906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com