[Vue] - Vue Methods

Soozoo·2024년 9월 27일

Vue

목록 보기
10/23

Vue Methods

Vue.js에서 Methods(메서드)는 Vue 인스턴스 내에서 정의된 사용자 정의 함수입니다. 주로 이벤트 핸들링데이터 처리를 위해 호출되며, Vue 컴포넌트의 동작을 정의하는 중요한 역할을 합니다. Vue의 methods 옵션을 사용하여 메서드를 정의할 수 있습니다.

주요 특징:

  • 이벤트 처리: 버튼 클릭, 폼 제출 등 사용자 상호작용에 반응하여 특정 동작을 실행할 수 있습니다.
  • 데이터 처리: 데이터의 변경, 계산, 검증 등 다양한 데이터 관련 작업을 수행할 수 있습니다.
  • Vue 인스턴스에 접근: 메서드 내에서 this를 사용하여 Vue 인스턴스의 데이터(data), 컴퓨티드 속성(computed), 프로퍼티(props), 그리고 다른 메서드에 접근할 수 있습니다.

기본 사용법:

methods는 Vue 컴포넌트의 하나의 옵션으로, methods 객체 안에 여러 메서드를 정의할 수 있습니다.

예시:

<template>
  <div>
    <p>{{ message }}</p>
    <button @click="reverseMessage">메시지 뒤집기</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  methods: {
    reverseMessage() {
      this.message = this.message.split('').reverse().join('');
    }
  }
}
</script>

위 예시에서는 reverseMessage라는 메서드를 정의하여, 버튼을 클릭하면 message 문자열을 뒤집습니다. 메서드 내부에서 this를 사용해 data에 접근하고 값을 변경할 수 있습니다.

Vue Methods의 특징

1. 이벤트 핸들러로 사용:

methods는 주로 이벤트와 함께 사용되며, 특정 이벤트가 발생할 때 호출됩니다.

<button @click="sayHello">Hello!</button>
methods: {
  sayHello() {
    alert('Hello, World!');
  }
}

2. 데이터 변경:

methods 내에서 this를 사용해 Vue 인스턴스의 data를 변경할 수 있습니다.

<button @click="increment">숫자 증가</button>
data() {
  return {
    counter: 0
  }
},
methods: {
  increment() {
    this.counter++;
  }
}

3. 메서드 간 호출:

하나의 메서드에서 다른 메서드를 호출할 수 있습니다.

methods: {
  firstMethod() {
    console.log('First method called!');
  },
  secondMethod() {
    this.firstMethod();  // 다른 메서드 호출
  }
}

4. Vue 인스턴스 접근:

메서드 내부에서 this 키워드를 사용해 Vue 인스턴스의 data, props, computed, 그리고 다른 메서드에 접근할 수 있습니다.

methods: {
  updateTitle() {
    this.title = 'Updated Title';  // data 속성 변경
  }
}

5. 비동기 작업:

Vue 메서드에서는 비동기 작업을 처리할 수 있습니다. 예를 들어, 서버로부터 데이터를 가져오는 비동기 작업을 methods 내에서 처리할 수 있습니다.

methods: {
  async fetchData() {
    try {
      const response = await fetch('<https://api.example.com/data>');
      const data = await response.json();
      this.data = data;
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }
}

Vue Methods와 Computed의 차이점

  • Methods: 매번 호출될 때마다 함수가 실행됩니다. 즉, 데이터에 변화가 없어도 호출 시마다 메서드가 실행됩니다.
  • Computed: 종속된 데이터가 변경되었을 때만 재계산됩니다. 성능 면에서 효율적이며, 데이터 변경에 따라 자동으로 값을 갱신합니다.

차이점 예시:

  • methods 사용:
<p>{{ calculateValue() }}</p>
methods: {
  calculateValue() {
    return this.number * 2;
  }
}

이 경우, 템플릿이 다시 렌더링될 때마다 calculateValue가 실행됩니다.

  • computed 사용:
<p>{{ doubledValue }}</p>
computed: {
  doubledValue() {
    return this.number * 2;
  }
}

computed는 종속된 데이터(this.number)가 변경될 때만 실행되므로 더 효율적입니다.

메서드와 Vue 라이프사이클

Vue의 라이프사이클 훅(created, mounted 등)에서도 메서드를 호출하여 컴포넌트 초기화 작업을 할 수 있습니다.

mounted() {
  this.fetchData();  // 컴포넌트가 마운트된 후 데이터를 가져옴
}

요약

  • Vue 메서드는 이벤트 처리, 데이터 변경 및 비동기 작업을 처리하는 데 사용됩니다.
  • methods 내부에서는 this를 사용해 Vue 인스턴스에 접근할 수 있으며, 다른 메서드 간에도 호출이 가능합니다.
  • methods매번 호출 시 실행되며, 특정 계산이 자주 필요하지 않은 경우에 적합합니다.
<!DOCTYPE html>
<html>
<head>
  <title>Moose count</title>
  <style>
    #app {
      border: dashed black 1px;
      width: 250px;
      padding: 10px;
    }
    img {
      width: 100%;
    }
    button {
      margin: 10px;
      padding: 5px 10px;
    }
    #app > div {
      width: 200px;
      height: 100px;
      background-color: lightcoral;
    }
    #app span {
      font-weight: bold;
      font-family: 'Courier New', Courier, 			monospace;
      margin: 20px;
    }

  </style>
</head>
<body>

<h1>Example: Passing Arguments with Methods</h1>

<div id="app">
  <img v-on:mousemove="mousePos" src="img_moose.jpg" width="300" height="300">
  <div  v-bind:style="{backgroundColor:'hsl('+xPos+',80%,80%)'}">
    <br><span>xPos: {{ xPos }}</span><br><span>yPos: {{ yPos }}</span>
  </div>
  <p>{{ "Moose count: " + count }}</p>
  <button v-on:click="addMoose(1)">+1</button>
  <button v-on:click="addMoose(5)">+5</button>
  <button v-on:click="addMoose(-1)">-1</button>
  <button v-on:click="addMoose(-5)">-5</button>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        count: 0,
        xPos: 0,
        yPos: 0
      }
    },
    methods: {
      addMoose(number) {
        this.count+=number
      },
      mousePos(event){
      	this.xPos = event.offsetX
        this.yPos = event.offsetY
      }
    }
  })
 app.mount('#app')
</script>

</body>
</html>
profile
넙-죽

0개의 댓글