search-bar.vue 2.23 KB
<template>
  <view class="search-bar">
    <view class="search-bar__icon">
      <zui-icon name="search"></zui-icon>
    </view>
    <view v-if="keyboard" class="search-bar__input" @click="onKeyboard">
      <text v-if="model">
				<text>{{ model }}</text>
			</text>
      <text v-else class="placeholder">{{ placeholder }}</text>
    </view>
    <input v-else class="search-bar__input" :type="type" confirm-type="search" :placeholder="placeholder" :value="model" @input="onInput" @confirm="onConfirm" />
    <view v-if="model" class="search-bar__icon clear" @click="onClear">
      <zui-icon name="close"></zui-icon>
    </view>
  </view>
</template>

<script>
let inputTimer = null;

export default {
  props: {
    value: String,
    type: {
      type: String,
      default: 'search',
    },
    placeholder: {
      type: String,
      default: '请输入搜索内容'
    },
    auto: {
      type: Boolean,
      default: false
    },
    keyboard: {
      type: Boolean,
      default: false
    },
  },
  data: function() {
    return {
      model: this.value
    };
  },
  watch: {
    value: function(val) {
      this.model = val;
    }
  },
  methods: {
    onKeyboard: function() {
      this.$emit('keyboard');
    },
    onInput: function(e) {
      this.model = e.target.value;
      this.$emit('input', e.target.value);
      if (this.auto) {
        if (inputTimer) {
          clearTimeout(inputTimer)
        }
        inputTimer = setTimeout(() => {
          this.$emit('confirm');
        }, 500);
      }
    },
    onClear: function() {
      this.model = '';
      this.$emit('input', '');
      this.$emit('clear', '');
      this.$nextTick(() => {
        this.$emit('confirm');
      });
    },
    onConfirm: function() {
      this.$emit('confirm');
    },
  }
}
</script>

<style lang="scss">
.search-bar {
  background-color: $color-field;
  height: 70upx;
  border-radius: 35upx;
  display: flex;
  align-items: center;
  padding: 0 $padding-md;
  &__icon {
    font-size: $font-lg;
    color: $color-text;
    &.clear {
      color: $color-border;
    }
  }
  &__input {
    flex: auto;
    padding: 0 10upx;
    font-size: $font-md;
    background-color: transparent;
    .placeholder {
      color: $color-text-minor;
    }
  }
}
</style>