您好,欢迎来到汇意旅游网。
搜索
您的当前位置:首页vue 简单自动补全的输入框的示例

vue 简单自动补全的输入框的示例

来源:汇意旅游网

实现一个输入框,输入信息后显示由后台返回的数据,供用户选择,之前用的elm的组件,不过那个有点大。。简单的情况下自己实现一个也能满足要求。。应该吧。。

主题包括一个input用于输入,一个div用于展示数据,div里面是数据项item

当在input中按下回车时,会根据信息去后台获取数据,如果用户点击了别的地方,input失去焦点,则提示的div也应该收起来

bug:

在blur事件中,如果直接将isShow设置为false会出问题,先失去焦点,显示面板消失,所以你的点击不会被监听到。。设置一个计时器,在点击之后10ms后将面板收起来,问题解决。。

显示div将内容撑开,改变其他组件布局,设置div的属性,即可,高度设为0,z-index很大,就不会改变其他组件位置

height: 0;
z-index: 999;
<template>
 <div class="container">
 <input v-model="msg" @keyup.enter="search" class="msg" @blur="blur"/>
 <div class="select-panel">
 <div v-show="isShow" v-for="w in words" class="select-item" @click="click_item(w)">{{w['content']}}</div>
 </div>
 </div>
</template>

简单实现代码

<template>
 <div class="container">
 <input v-model="msg" @keyup.enter="search" class="msg" @blur="blur"/>
 <div class="select-panel">
 <div v-show="isShow" v-for="w in words" class="select-item" @click="click_item(w)">{{w['content']}}</div>
 </div>
 </div>
</template>

<script>
 import {search_word} from "../api/word-api";

 export default {
 name: "auto-complete",
 data() {
 return {
 msg: '',
 words: [],
 isShow: false
 }
 },
 computed: {},

 methods: {
 blur() {
 setTimeout(() => {
 this.isShow = false
 },
 200)
 },
 async search() {
 console.log('search msg', this.msg)
 this.words = await search_word(this.msg)
 console.log(this.words)
 this.isShow = true
 },
 click_item(w) {
 console.log('click word', w)
 this.$emit('add_word', w)
 }
 },

 }
</script>

<style scoped>

 .container {
 display: flex;
 flex-grow: 0;
 flex-shrink: 0;
 box-sizing: border-box;
 }

 .msg {
 margin: 5px;
 }

 .select-panel {
 height: 0;
 z-index: 999;

 }

 .select-item {
 /*height: 0;*/
 z-index: 999;
 margin: 1px;
 padding: 2px;
 background: #fff;
 opacity: 0.8;
 }
</style>

Copyright © 2019- hids.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务