이벤트 핸들러

o:kcalb·2024년 2월 20일

Vue

목록 보기
3/28
post-thumbnail

이벤트 핸들러 - HTML 클릭 시 코드 실행하는 법

클릭 이벤트

기존 js

<button type="button" onClick="동작">허위매물신고</button>

Vue

<button type="button" v-on:click="동작">허위매물신고</button>
<button type="button" @:click="동작">허위매물신고</button>

예시1

<template>
  <div>
    <h4>역삼동 원룸</h4>
    <p>XX 만원</p>
    <button type="button" v-on:click="report++">허위매물신고</button>
    <p>신고 수: {{ report }}</p>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){// 데이터 보관통
    return {
      report: 0, //신고수
    }
  }
}
</script>

예시2 (methods 보관함)

  • js가 길 경우 함수에 정의
  • 함수는 넣는 공간이 따로 있음 = methods: {}
  • 만약 data함 등에서 만든 변수를 갖고 오고 싶을 때는 this.데이터명 사용
  • @이벤트에 함수 호출 시 () 사용하지 않음
<template>
  <div>
    <h4>역삼동 원룸</h4>
    <p>XX 만원</p>
    <!-- 함수에 () 달지 않음 -->
    <button type="button" v-on:click="increase">허위매물신고</button>
    <p>신고 수: {{ report }}</p>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){// 데이터 보관통
    return {
      report: 0, //신고수
    }
  },
  methods: { //methods 함수 보관함
    increase(){
      this.report += 1; //this 필수
    },
  },
}
</script>

예시3

  • 각 제품 내 신고버튼 눌렀을 경우 누른 제품의 신고 수만 증가하게 함
  • img src를 js로 부를 때 엑박 뜨는 경우: require 사용(참고)
    - require는 파일 외부의 데이터를 가져올 때 사용하는 JS 내장함수임. HTML과 달리 img src를 JS에서 불러오면 String으로 인식됨.
<template>
  <div class="menu">
    <!--  -->
    <a href="#" v-for="(item, idx) in menu" :key="idx">{{ item }}</a>
  </div>

  <div v-for="(item, idx) in products_obj" :key="idx">
    <img :src="item.img">
    <h4>{{ item.tit }}</h4>
    <p>{{ item.price }} 만원</p>
    <button type="button" v-on:click="item.report += 1">허위매물신고</button>
    <p>신고 수: {{ item.report }}</p>
    <hr>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){// 데이터 보관통
    return {
      price1 : 60,
      price2 : 70,
      products: ['역삼동 원룸'],
      products_obj: [
        {
          tit: '역삼동 원룸',
          price: 60,
          img: require('./assets/room0.jpg'),
          report: 0,
        },
        {
          tit: '천호동 원룸',
          img: require('./assets/room1.jpg'),
          price: 70,
          report: 0,
        },
        {
          tit: '마포구 원룸',
          img: require('./assets/room2.jpg'),
          price: 80,
          report: 0,
        },
      ],
      menu: ['Home', 'Shop', 'About'],
      blueColor: 'color: blue',
    }
  },
  components: {
  }
}
</script>

profile
모든 피드백 받습니다 😊

0개의 댓글