Vue3 (사이트 제작 5 - Movie.js의 반응성)

최충열·2022년 6월 15일
post-thumbnail
이벤트는 Store에 저장

검색결과 도출하는 이벤트를 Search.vue에서 movie.js => actions로 이동한다.
이유는 중앙집중방식을 이용할꺼기 때문이다.

import axios from 'axios'

export default {
  // module!
  namespaced: true,
  // data!
  state: () =>{
    return {
      movies: [],
      message: '',
      loading: false
    }
  },
  // computed!
  getters: {},
  // methods!
  // 변이 이것을 통해 수정이 가능하다
  mutations: {
    updateState(state, payload) {
      // ['movies', 'message', 'loading']
      Object.keys(payload).forEach(key => {
        state[key] = payload[key]
      })
    },
    resetMovies(state) {
      state.movies = []
    }
  },
  // 비동기
  actions: {
    async searchMovies({ commit }, payload) {
        const { title, type, number, year } = payload

        // Search movies... 
        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
        })
    }
  }
}

search. vue

dispatch() 메쏘드를 사용하여 title부터 year값까지 받아온다, 결국 이 값은 movie.js에 있는 actions로 값을 받게되며 그 값은 payload로 받을수 있다.
commit을 사용하여 mutations를 작동시킨다. mutataions이 변이를 사용하기때문에 key값을 할당하여 내 검색어를 state[key]에 할당한다.

<script>
 methods: {
    async apply() {
      // Store의 Mutations를 실행할때는 .commit() / Actions를 실행할 때는 .dispatch() 사용 
      this.$store.dispatch('movie/searchMovies', {
        title: this.title,
        type: this.type,
        number: this.number,
        year: this.year
      })
      
    }
  }
</script>

MovieList.vue

store에서 받은값을 state.movie.movies를 통해서 return으로 보관하고 computed를 사용해서 반응성을 도출하게된다.
:movie="movie" 원하는 이름의 props로 전달해줄려고 만들었다.

<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!
  computed: {

    movies() {
      return this.$store.state.movie.movies
    }
  }
}
</script>

MovieItem.vue

Item의 값을 얻기위해 Props로 movie를 받고
그 값의 Title만 생성한다.

<template>
  <div>
    {{ movie.Title }}
  </div>
</template>

<script>
export default {
  props: {
    movie: {
      type: Object,
      // default: function () { return {} }
      default: () => ({})

    }
  }
}
</script>

아직 배울게 너무많고 이해가 잘 안된다.. 더 공부하자

profile
프론트엔드가 되고싶은 나

0개의 댓글