移动端input输入历史建议

2019-09-27 19:19:20 浏览数 (2)

基于vant输入历史记录源码

historyInput.gif

使用

代码语言:javascript复制
<template>
  <div class="hello">
    <historyInput label="备注:" placeholder="请输入备注内容" v-model="msg" historyKey="001010" :maxHistory="10"></historyInput>
    <historyInput label="张荣武:" placeholder="请输入张荣武内容" v-model="name" historyKey="001011" :maxHistory="4"></historyInput>
    <historyInput label="开发人员:" placeholder="请输入开发人员内容" v-model="msg" historyKey="001012" :maxHistory="2"></historyInput>
    <historyInput label="QQ:" placeholder="请输入QQ" v-model="QQ" historyKey="001014" :maxHistory="8"></historyInput>
  </div>
</template>

<script>
import historyInput from "./historyInput"
export default {
  components: {
    historyInput,
  },
  name: 'HelloWorld',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App',
      QQ: "3153256054",
      name: "张荣武"
    }
  }
}
</script>

<style scoped>
</style>

historyInput关键代码

代码语言:javascript复制
 <div class="historyInput">
    <van-field :label="label" :placeholder="placeholder" autosize v-model="cMessage" @focus="inputFocus()" @blur="inputBlur()" @input="inputChange" />
    <div v-show="bzfirstResponder" class="bz-first-responder">
      <div class="bz-first-item" @click="bzEvent(item)" v-for="(item, index) in bzInputHistory" :key="index">{{item}}</div>
    </div>
  </div>

通过计算属性分离value父子组建之间互相绑定的影响

代码语言:javascript复制
 computed: {
    cMessage: {
      get() {
        return this.value;
      },
      set(val) {
        this.newValue = val;
      }
    }
  },

数据存储逻辑

代码语言:javascript复制
var list = JSON.parse(window.localStorage.getItem(this.historyKey));
        if (this.value != null) {
          if (list != null) {
            if (list.indexOf(this.value) == -1) {//不存在

              if (list.length >= this.maxHistory) {
                list.splice(this.maxHistory - 1, list.length - this.maxHistory   1)
              }
            } else {
              for (var i = 0; i < list.length; i  ) {
                if (list[i] == this.value) {
                  list.splice(i, 1);
                  break;
                }
              }
            }
            list.splice(0, 0, this.value)
          } else {
            list = [];
            list.push(this.value)
          }
          window.localStorage.setItem(this.historyKey, JSON.stringify(list))
          this.bzInputHistory = JSON.parse(window.localStorage.getItem(this.historyKey));
        }

0 人点赞