// components/w-search-picker/index.ts // 组件不支持简单的双向绑定,需要使用input和confirm事件来实现。 Component({ options: { multipleSlots: true, styleIsolation: "shared", }, /** * 组件的属性列表 */ properties: { value: { type: [String, Number] as any, value: "", observer: "_value", }, searchValue: { type: String, value: "", observer: "_searchValue", }, /** 是否显示 */ show: { type: Boolean, value: false, observer: "_show", }, /** * 列数据 * @example 单列 [{ text: a, value: 1 }, { text: b, value: 2 }] */ columns: { type: Array as any, value: [], }, /** * 可见的选项个数 */ visibleItemCount: { type: Number, value: 6, }, itemHeight: { type: Number, value: 46, }, searchLoading: { type: Boolean, value: false, observer: "_searchLoading", }, placeholder: { type: String, value: "请输入搜索关键词", }, }, /** * 组件的初始数据 */ data: { innerShow: false, showAfterLeave: false, innerValue: "" as any, // 单列时为string, 多列为array defaultIndex: 0, // 默认选中的index 单行显示的 innerLoading: false, searchName: "", }, /** * 组件的方法列表 */ methods: { onSubmit() { this.setData({ show: false, value: this.data.innerValue, }); const columns = this.data.columns || []; let detail: any = {}; if (this.data.innerValue) { columns.forEach((item: any) => { if (item.value === this.data.innerValue) { detail = item; } }); } this.triggerEvent("confirm", detail); this.triggerEvent("input", this.data.innerValue); }, onChange(event: any) { const detail = event.detail.value; this.setData({ innerValue: detail.value, }); this.triggerEvent("change", detail); }, onClose() { this.triggerEvent("cancel"); }, onSearchChange(event: any) { this.triggerEvent("search-change", event.detail); }, onSearch(event: any) { // 如果在搜索中,不允许搜索 if(this.data.innerLoading) { return; } this.setData({ searchValue: event.detail, }); this.triggerEvent("search", event.detail); }, onAfterLeave() { this.setData({ showAfterLeave: true, }); }, onBeforeEnter() { this.setData({ showAfterLeave: false, }); }, _show() { // 单行显示 需要设置默认选中的index let defaultIndex = 0; let innerValue = this.data.innerValue; if (this.data.show) { // 单行显示 this.data.columns.forEach((item: any, index: number) => { if (item.value === this.data.value) { defaultIndex = index; } if (!innerValue) { innerValue = item.value; } }); } this.setData( { defaultIndex, innerValue, }, () => { this.setData({ innerShow: this.data.show, }); } ); }, _value() { this.setData({ innerValue: this.data.value, }); }, _searchLoading() { this.setData({ innerLoading: this.data.searchLoading, }); }, _searchValue() { this.setData({ searchName: this.data.searchValue, }); }, }, });