-
Vue 프로젝트 영화 검색프로젝트/영화 검색 (Vue) 2021. 8. 2. 14:16
Vue 프로젝트 영화 검색
1. /src/store/movie.js 영화 검색 코드 작성
- /src/components/Search.vue 메소드에 있는 apply() 코드를 잘라내서 가져옴
/* /src/store/movie.js */ import axios from 'axios' export default { namespaced: true, state: () => ({ movies: [], message: '', loading: false }), getters: {}, mutations: { updateState(state, payload) { Object.keys(payload).forEach(key => { state[key] = payload[key] }) }, resetMovies(state) { state.movies = [] } }, // 비동기 actions: { async searchMovies({ commit }, payload) { const { title, type, number, year } = payload const OMDB_API_KEY = '7035c60c' const res = await axios.get(`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=1`) const { Search, totalResults } = res.data commit('updateState', { movies: Search }) } } }
2. /src/components/Search.vue 코드 수정
<!-- /src/components/Search.vue --> <template> <div class="container"> <input ...생략 placeholder="Search for Movies, Series & more" @keyup.enter="apply" /> <div class="selects"> <select ...생략 </select> </div> <button ...생략 </button> </div> </template>
<script> export default { data() { ...생략 }, methods: { async apply() { this.$store.dispatch('movie/searchMovies', { title: this.title, type: this.type, number: this.number, year: this.year }) } } } </script>
Store의 Mutations를 실행 .commit(), Actions를 실행 .dispatch()
3. /src/components/MovieList.vue 코드 수정
- /src/store/movie.js 데이터를 가져옴
<!-- /src/components/MovieList.vue --> <template> <div class="container"> <div class="inner"> <MovieItem v-for="movie in movies" :key="movie.imdbID" :movie="movie" /> </div> </div> </template>
<script> import MovieItem from '~/components/MovieItem' export default { components: { MovieItem }, computed: { movies() { return this.$store.state.movie.movies } } } </script>
4. /src/components/MovieItem.vue 코드 작성
<!-- /src/components/MovieItem.vue --> <template> <div>{{ movie.Title }}</div> </template>
<script> export default { props: { movie: { type: Object, default: () => ({}) } } } </script>
결과
'프로젝트 > 영화 검색 (Vue)' 카테고리의 다른 글
Vue 프로젝트 영화 목록 ID 중복 제거 (0) 2021.08.03 Vue 프로젝트 영화 검색 추가 요청 (0) 2021.08.03 Vue 프로젝트 Vuex(Store) 구성 (0) 2021.08.02 Vue 프로젝트 Vuex(Store) 개요 (0) 2021.08.01 Vue 프로젝트 Search - 버튼 (0) 2021.08.01