搜索功能复杂逻辑的思考与项目总结

文章描述了一个Vue组件SearchInput,使用Vuex管理状态,当输入框长度达到最大限制或变为0时,调用相应服务获取数据。同时,组件还监听field变化,清空输入框内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

src\components\SearchInput\index.vue

<template>
  <div class="search-wrap">
    <input
      type="text"
      :placeholder="placeholder"
      :maxlength="maxlength"
      :value="inputValue"
      @input="searchData($event)"
    />
  </div>
</template>

<script>
import { computed, ref, watch } from 'vue'
import { useStore } from 'vuex'

import { formatUserDate, getNowDate } from '@/libs/utils'
import getData from '@/services'
export default {
  name: 'SearchInput',
  props: {
    placeholder: String,
    maxlength: Number,
  },
  setup(props) {
    const inputValue = ref(''),
      store = useStore(),
      state = store.state

    const searchData = (e) => {
      inputValue.value = e.target.value

      const field = computed(() => state.field).value
      // 输入长度跟设定的maxlength相等时,调用接口
      if (inputValue.value.length === props.maxlength) {
        getData(store, field, formatUserDate(inputValue.value))
      } else if (inputValue.value.length === 0) {
        getData(store, field, getNowDate(field))
      }
    }

    /**
     * 监听 field 变化,清空输入框的值
     */
    watch(
      () => {
        return state.field
      },
      () => {
        inputValue.value = ''
      }
    )
    return {
      inputValue,
      searchData,
    }
  },
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值