需求
添加注解时需要根据 Input 输入值下拉显示提示信息,并可选
步骤
1.为目标 Input 绑定 on-focus
和 on-blur
事件,聚焦时显示,失焦时隐藏;下拉提示信息使用 ul,li
标签显示,浮动样式使用 position
属性实现(设置为 Input 的 position 为 relative,ul 标签的 position 为 absolute);
2. 使用 Vue computed 属性,根据所需逻辑,实时计算所需要显示的列表数据(此方法不支持调接口获取数据,如需按输入调用接口,可在 Input on-focus
方法中调用接口);
3. ul 标签使用 v-show
判断当前是否应显示列表(showAnnotationTip && getAnnotationKeyList().length > 0
),使用 @mousedown
方法监听鼠标选择并赋值。此外,需要为已选择的 key 设置高亮样式。
代码
html 部分
<Form
@submit.native.prevent
ref="textForm"
:model="formData"
>
...
<Form-item>
<Input
v-model.trim="formData.keyName"
placeholder="请输入"
@on-focus="showTip()"
@on-blur="hiddenTip()"
style="width: 95%; position: relative"
/>
<ul
class="ul-wrapper"
v-show="showAnnotationTip && getAnnotationKeyList().length > 0"
>
<li
v-for="annotationKey in getAnnotationKeyList()"
:key="annotationKey"
:style="formData.keyName === annotationKey ? 'color: rgba(59,124,255,1);cursor: pointer; z-index: 200': 'cursor: pointer; z-index: 200'"
@mousedown="selectedKey(annotationKey)"
>
{{ annotationKey }}
</li>
</ul>
</Form-item>
</Form >
js 部分
export default {
data() {
return {
showAnnotationTip: false,
formData: {
keyName: ''
}
}
},
computed: {
providerOptions(){
// 根据所需逻辑计算当前需要显示的提示信息
return ['1111', '2222', '3333'];
}
},
methods: {
showTip(){
this.showAnnotationTip = true;
},
hiddenTip(){
this.showAnnotationTip = false;
},
getAnnotationKeyList() {
if(!this.formData.keyName){
return this.providerOptions;
}
//根据当前输入内容筛选显示数据
return this.providerOptions.filter(item => item.indexOf(this.formData.keyName) !== -1);
},
selectedKey(annotationKey) {
this.formData.keyName = annotationKey;
this.showAnnotationTip = false;
}
}
}
css 部分
.ul-wrapper {
position: absolute;
margin: 5px;
padding: 8px;
min-width: 210px;
border-radius: 4px;
background-color: #fff;
list-style: none;
z-inde: 100;
max-height: 232px;
overflow-y: auto;
box-sizing: border-box;
}