vue vuetify 实现智能联想

2020-11-03 14:51:18 浏览数 (2)

使用 Vuetify 中的 v-menu 组件实现,控制光标焦点,在输入框获取的焦点时弹出联想词汇菜单,支持上下按键选中内容,菜单位置,样式按需调整即可

数据获取方面通过监听输入框内容变化,调用对应接口获取数据

注意

如果产品功能要求极高的性能,要加防抖和节流处理

代码语言:javascript复制
<template>
  <div v-on:keyup.enter="search">
    <v-menu offset-y>
      <template v-slot:activator="{ on }">
        <v-text-field
          solo
          hide-details
          label="请输入关键词"
          append-icon="search"
          v-model="text"
          class="input-search"
          autocomplete="off"
          v-on="on"
          ref="search"
        ></v-text-field>
      </template>
      <v-list v-if="items.length > 0" class="border-list" dense>
        <v-list-item v-for="(item, index) in items" :key="index" @click="itemClick(item)">
          <v-list-item-title>{{ item.name }}</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </div>
</template>
<script>
export default {
  data () {
    return {
      text: '',
      showSelect: true,
      items: []
    }
  },
  watch: {
    text: 'inputHandle'
  },
  methods: {
    itemClick (item) {
      this.text = item.name
      this.$refs.search.blur()
      // this.$router.push() 
    },
    inputHandle (text) {
      if (text.trim() !== '') {
        this.showSelect = true
        setTimeout(() => {
          this.getEntity()
        }, 300)
      }
    },
    getEntity () {
      // 请求接口更新 items 数据
      this.items = [
        {
          key: '1234',
          name: '1234'
        },
        {
          key: 'abc',
          name: 'abc'
        },
        {
          key: 'def',
          name: 'def'
        },
        {
          key: 'ccc',
          name: 'ccc'
        },
        {
          key: 'ccc',
          name: 'ccc'
        },
        {
          key: 'ccc',
          name: 'ccc'
        }
      ]
    },
    search () {
      this.$refs.search.blur()
      console.log(this.text)
      // this.$router.push()
    }
  }
}
</script>
<style scoped>
.input-search {
  width: 40%;
  margin: auto;
}
.width-20-percent {
  width: 20%;
}
.img-div {
  margin: 16vh 0 40px 0;
  text-align: center;
}
.v-menu__content {
  box-shadow: none !important;
}
.border-list {
  border: 1px solid #eee !important;
}
</style>

0 人点赞