vue实现搜索中点击键盘上键、下键时按下搜索对应出来的相关关键字内容的切换???百度搜索

实现思路:
1.在按下键盘上键,下键时候,把li标签的下标与class样式进行一个绑定
2.再点击上键的时候,就要考虑起始的下标值,不能是0,因为开始的时候还没有到下表为0的li上,
特殊情况:当按到最小的下标时怎么处理下标
3.在点击下键的时候,
特殊情况:当按到最大的下标的时候应该怎么做?
在这里插入图片描述

子组件中=》

<div class="search">
    <div>
      <i class="fa fa-search" aria-hidden="true"></i>
      <input
        type="search"
        v-model="title"
        @input="send"
        @keyup.enter="sendTwo"
        @keydown.up="up"
        @keydown.down="down"
        @blur="hidden"
      />
    </div>
    <p @click="cancel">取消</p>
    <ul class="list" v-if="show">
      <li v-for="(item,key) in list" :key="key" :class="{bg:key==index}">{
   
   {item}}</li>
    </ul>
  </div>
data() {
    return {
      title: "",
      index: -1,
      show: true
    };
  },
  props: {
    list: {
      type: Array,
      default: []
    }
  },
  methods: {
    send() {
      this.$emit("sendData", this.title);
    },
    sendTwo() {
      this.send();
    },
    cancel() {
      this.title = "";
      this.$emit("sendData", this.list);
    },
    up() {
      if (this.index == -1 || this.index == 0) {
        this.index = this.list.length - 1;
      } else {
        this.index--;
      }
      this.title = this.list[this.index];
    },
    down() {
      if (this.index < this.list.length - 1) {
        this.index++;
      } else {
        this.index = 0;
      }
      this.title = this.list[this.index];
    },
    hidden() {
      this.show = false;
      this.title = "";
    }
  }
css
.bg {
  background-color: #eee;
  color: #fff;
}
.list {
  width: 100%;
  padding: 0 50px;
  box-sizing: border-box;
  li {
    height: 30px;
    line-height: 30px;
    border-bottom: 1px solid #ccc;
  }
}
.search {
  width: 100%;
  display: flex;
  height: 40px;
  align-items: center;
  justify-content: space-around;
  flex-wrap: wrap;
  div {
    width: 90%;
    input {
      width: 90%;
      height: 30px;
      border: 1px solid #000;
      border-radius: 20px;
      outline: none;
      text-indent: 25px;
    }
    i {
      position: relative;
      top: 2px;
      left: 20px;
    }
  }
}

父子件=》

  <Search @sendData="getData" :list = "lists"></Search>
 data() {
    return {
      title: "",
      list: [],
      lists: []
    };
  },
  methods: {
    getData(data) {
      this.title = data;
      this.lists = [];
      this.list.forEach(v => {
        if (v.indexOf(this.title) !== -1) {
          this.lists.push(v);
        }
      });
      if (this.title == "") {
        this.lists = [];
      }
     }
  },
  mounted() {
    this.$axios.get("data.json").then(res => {
      this.list = res.data;
    });
  }

猜你喜欢

转载自blog.csdn.net/lqlq54321/article/details/106766550
今日推荐