inblog logo
|
devleekangho
    Vue.js

    [Vue.js] v-for와 이벤트 핸들러

    KangHo Lee's avatar
    KangHo Lee
    May 28, 2025
    [Vue.js] v-for와 이벤트 핸들러
    Contents
    1. v-for 반복문2. 이벤트 핸들러3. 전체 코드 + 결과

    1. v-for 반복문

    <div v-for="(p, i) in products" :key="i"> <h4>{{ p }}</h4> <p>{{ prices[i]}}</p> <button @click="increase(i)">허위매물신고버튼</button> <span>신고수 : {{reportCount[i]}}</span> </div>
    • i 는 인덱스
      • key → 각 항목을 구별할 수 있도록 반드시 고유한 값 사용
      • 예: :key="item.id" 또는 :key="index"
    • p 는 products 라는 리스트의 요소
      • products[i] 와 같다.

    2. 이벤트 핸들러

    <button @click="increase(i)">허위매물신고버튼</button> <span>신고수 : {{reportCount[i]}}</span>
    • v-on:click=”자바스크립트내용” 으로 써도 되지만 @이벤트이름이 더 편리하다
      • @적고 Ctrl + Space → 다양한 이벤트 확인 가능
    <script> export default { name: "App", data() { return { reportCount : [0, 0, 0], menus : ['Home', 'Shop', 'About'], prices: ['60', '70', '80'], products: ["역삼동원룸", "천호동원룸", "마포구원룸"], }; }, methods : { increase(i) { this.reportCount[i] += 1; } }, components: {}, }; </script>
    • methods 에 자바스크립트 함수를 작성하면 된다.
      • data에서 변수를 가져오려면 this. 를 붙여야 한다.

    3. 전체 코드 + 결과

    notion image
    <template> <div class="menu"> <a v-for="a in menus" :key="a"> {{a}}</a> </div> <div v-for="(product, i) in products" :key="i"> <h4>{{ product }}</h4> <p>{{ prices[i]}}</p> <button @click="increase(i)">허위매물신고버튼</button> <span>신고수 : {{reportCount[i]}}</span> </div> </template> <script> export default { name: "App", data() { return { reportCount : [0, 0, 0], menus : ['Home', 'Shop', 'About'], prices: ['60', '70', '80'], products: ["역삼동원룸", "천호동원룸", "마포구원룸"], }; }, methods : { increase(i) { this.reportCount[i] += 1; } }, components: {}, }; </script>
     
    Share article
    Contents
    1. v-for 반복문2. 이벤트 핸들러3. 전체 코드 + 결과

    devleekangho

    RSS·Powered by Inblog