메시지를 생성하려면 Vuex 저장소에 데이터를 저장해야한다.
지금까지는 "Coaches 모듈"만 만들어보았다.
이제 요청을 관리하려면 "Requests 모듈"을 만들어야 한다.
# Request 모듈
Request모듈에서도 네임스페이스를 사용하자.
전역 저장소에 그냥 합칠 수도 있지만, 이번에는 그렇게 하지 않았다.
state는 요청을 관리해야한다.
import mutations from './mutations.js';
import actions from './actions.js';
import getters from './getters.js';
export default {
namespaced: true,
state() {
return {
requests: [],
};
},
mutations,
actions,
getters,
};
그리고 모든 요청에는 특정 코치 id가 존재한다.
이 코치 id가 우리의 id와 일치하면 우리가 보게 될 요청이다.
다른 요청은 보이지 않는다.
## mutations.js
mutation을 작성하자.
export default {
addRequest(state, payload) {
const request = payload;
state.requests.push(request);
},
};
## actions.js
actions.js를 작성하자.
export default {
contactCoach(context, payload) {
const newRequest = {
id: new Date().toISOString(), //지금 당장은 더미 id
coachId: payload.coachId, //들어오는 payload에 있다고 가정하고 coachId를 입력
userEmail: payload.email,
message: payload.message,
};
context.commit('addRequest', newRequest);
},
};
이제 ContactCoach.vue 컴포넌트에서 dispatch를 하자.
우리의 모듈은 네임스페이스가 적용되어 있으므로, requests 네임스페이스에 액세스해야한다.
Q. 메시지를 전송할 코치의 id는 어떻게 해야할까?
Contact버튼을 누르면 이 URL에 코치의 id가 포함되어있다.
ex: "http://localhost:8080/coaches/c1/contact"
{
path: '/coaches/:id',
component: CoachDetail,
props: true,
children: [{ path: 'contact', component: ContactCoach }],
},
router를 보면, contact는 child 라우트이다.
ContactCoach 컴포넌트는 CoachDetail의 자식 라우트. 따라서 id 매개변수를 가지게 된다.
따라서 id를 여기서 추출할 수 있다.
- props: true로 할 수도 있지만, 다른 접근법으로 ContactCoach에서 id를 가져와보자.
→ this.$route.params.id
this.$store.dispatch('requests/contactCoach', { //actions
coachId: this.$route.params.id,
email: this.email,
message: this.message,
});
마지막으로 이 페이지에서 나가지도록 하자.
this.$store.dispatch('requests/contactCoach', {
coachId: this.$route.params.id,
email: this.email,
message: this.message,
});
this.$router.replace('/coaches') //push대신 replace를 사용해서 이 페이지로 돌아갈 수 없도록.
이를 저장하고 나면, 이제 request를 보낼 수 있게 된다.
하지만 아직 reques가 Reqeusts페이지에서 보이지 않는다.
** 출처: 모든 내용은 Udemy Vue-완벽가이드 강의를 기반으로 작성하였습니다.
'Vue.js' 카테고리의 다른 글
[Udemy Vue 완벽가이드 Section16] 251. 활성 코치에 대한 요청 필터링하기 (0) | 2023.12.13 |
---|---|
[Udemy Vue 완벽가이드 Section16] 250. 수신 요청(메시지) 출력하기 (0) | 2023.12.13 |
[Udemy Vue 완벽가이드 Section16] 248. 연락처 양식 작업하기 (0) | 2023.12.13 |
[Udemy Vue 완벽가이드 Section16] 247. 양식 유효성 검사 추가하기 (0) | 2023.12.13 |
[Udemy Vue 완벽가이드 Section16] 246. Vuex에 코치 추가하기 (0) | 2023.12.12 |