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>