Vue.js/Way Home
[자동완성검색(1)] 입력한 값으로 시작하는 array값만 출력하기
Judith Hopps
2022. 10. 19. 18:39
반응형
목적 :
사용자 input한 데이터로 시작하는 list의 값만 출력하기
구현 :
1. input값에 v-model을 이용한다.
<input
class="form-control"
placeholder="휴게소를 입력해주세요"
type="text"
v-model="inputRest"
@input="showRestlist"
/>
2. v-model 값을 ref로 작성한다.
3. 검색창에 뜰 Array를 작성해준다.
- 서버에서 데이터 받을 경우에는 부모 컴포넌트에서 suspense를 작성해준다.
4. input할 때마다 list가 달라지게 computed로 작성해준다.
5. filter와 starsWith를 작성해서 restList를 작성해준다.
- (필터하고 싶은 array).startsWith("시작해야하는 문구") 식으로 작성해주면 된다.
아래 스크립트 참고.
<script lang="ts" setup>
import { ref, computed,defineProps,defineEmits } from "vue";
import axios from '../../../../modules/api/axios';
import type { HighwayData } from '../../../../modules/api/types/index';
let inputRest = ref('');
let highwayDataArray: string[] = [
'공통', '공지','나는'
];
const restList = computed(() => {
return highwayDataArray.filter((data) => data.startsWith(inputRest.value));
});
실행화면 :

반응형