在输入中,用户编写用于搜索产品的搜索短语。我想在用户停止键入后设置搜索。这里有一个很好的例子,但在Lightning Web Components中不起作用。当我开始写入搜索输入时,出现一个错误:";此页面有错误。你可能只需要刷新一下;
productList.html:
<lightning-input
type="search"
class="slds-var-m-bottom_small"
value={searchKey}
placeholder="Searching..."
onchange={handleSearchEvent}>
</lightning-input>
productList.js:
import { LightningElement, wire } from 'lwc';
import findProducts from '@salesforce/apex/ProductMaster.findProducts';
export default class ProductList extends LightningElement {
searchKey = '';
timeout = null;
@wire(findProducts, { searchKey: '$searchKey' })
products;
handleSearchEvent(event) {
const eventValue = event.target.value;
clearTimeout(timeout);
timeout = setTimeout(function (eventValue) {
this.searchKey = eventValue;
console.clear();
console.log('handleSearchEvent() -> this.searchKey: ' + this.searchKey);
}, 1000); // searching after 1s
}
}
如何设置超时?js控制台写:
console.log('handleSearchEvent() -> this.searchKey: ' + this.searchKey);
handleSearchEvent() -> this.searchKey: undefined
问题是需要显式设置函数中的this
绑定:
timeout = setTimeout(function (eventValue) {
this.searchKey = eventValue;
console.clear();
console.log('handleSearchEvent() -> this.searchKey: ' + this.searchKey);
}.bind(this), 1000);
但也许一个更简单的方法是使用一个箭头函数,它将隐含地绑定this
,我相信:
timeout = setTimeout((eventValue) => {
this.searchKey = eventValue;
console.clear();
console.log('handleSearchEvent() -> this.searchKey: ' + this.searchKey);
}, 1000);