[Vue-숙제] Vue로 만드는 직방 웹앱 : 4. 이벤트 핸들러로 허위매물 신고버튼 만들기
이번 게시글은 지난
https://ziaho0403.tistory.com/85
[Vue] Vue로 만드는 직방 웹앱 : 4. 이벤트 핸들러로 허위매물 신고버튼 만들기
안녕하세요. 이번 시간에는 이벤트 핸들러를 사용하는 방법에 대해 알아보도록 하겠습니다. 해당 프로젝트의 전체 소스는https://github.com/zziaho/vuedongsan GitHub - zziaho/vuedongsan: Vue로 만드는 직방웹
ziaho0403.tistory.com
게시글에서 참고하던 영상의 마지막에 나왔던 숙제에 대한 답을 만들어보는 게시글을 만들어보겠습니다.
사실 그 전의 영상들에서도 숙제가 있었는데, 따로 게시글로는 작성하지 않았습니다.
근데 남겨두면서 한번 더 정리하면 좋을거같아서 이번 숙제부터 게시글로 작성해보기로 했습니다.
Q. 각 원룸 매물별로 허위신고 버튼 만들기
A1. 전체 소스코드
<template>
<div class="menu">
<a v-for="(menu, index) in menus" :key="index">{{ menu }}</a>
</div>
<img alt="Vue logo" src="./assets/logo.png">
<div v-for="(product, index) in products" :key="index">
<h4>{{ product.name }}</h4>
<p>{{ product.price }}</p>
<button @:click="increseReportCnt(index)">허위매물신고</button> <span>신고수 : {{ product.reportCnt }}</span>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
products: [
{
name: '역삼동원룸',
price: '30만원',
reportCnt: 0,
},
{
name: '천호동원룸',
price: '50만원',
reportCnt: 0,
},
{
name: '마포구원룸',
price: '70만원',
reportCnt: 0,
},
],
menus: ['Home', 'Shop', 'About'],
reportCnt: 0,
}
},
methods: {
increseReportCnt(index) {
this.products[index].reportCnt += 1;
},
},
components: {
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.menu {
background: darkslateblue;
padding: 15px;
border-radius: 5px;
}
.menu a {
color: white;
padding: 10px;
}
</style>
A2. 설명
우선 products 데이터의 각각 Object에 reportCnt라는 default값이 0인 속성을 각각 추가해주었습니다.
products: [
{
name: '역삼동원룸',
price: '30만원',
reportCnt: 0,
},
{
name: '천호동원룸',
price: '50만원',
reportCnt: 0,
},
{
name: '마포구원룸',
price: '70만원',
reportCnt: 0,
},
이후 각각 매물들의 reportCnt값이 바인딩 되도록 값을 꽂아주고
<span>신고수 : {{ product.reportCnt }}</span>
신고 버튼을 눌렀을 때 파라미터로 index값을 넘겨주도록 설정하였습니다.
<button @:click="increseReportCnt(index)">허위매물신고</button>
그리고 마지막으로 increseReportCnt 함수를 아래와같이 변경하여
increseReportCnt(index) {
this.products[index].reportCnt += 1;
},
버튼을 클릭했을 때 index로 해당 매물을 찾아 그 매물의 reportCnt값이 1씩 오르도록 설정 해 주었습니다.
A3. 결과
해당 소스는
https://github.com/zziaho/vuedongsan
GitHub - zziaho/vuedongsan: Vue로 만드는 직방웹앱
Vue로 만드는 직방웹앱. Contribute to zziaho/vuedongsan development by creating an account on GitHub.
github.com
에 올려두었습니다.