Vue.js에서 Methods(메서드)는 Vue 인스턴스 내에서 정의된 사용자 정의 함수입니다. 주로 이벤트 핸들링과 데이터 처리를 위해 호출되며, Vue 컴포넌트의 동작을 정의하는 중요한 역할을 합니다. Vue의 methods 옵션을 사용하여 메서드를 정의할 수 있습니다.
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에 접근하고 값을 변경할 수 있습니다.
methods는 주로 이벤트와 함께 사용되며, 특정 이벤트가 발생할 때 호출됩니다.
<button @click="sayHello">Hello!</button>
methods: {
sayHello() {
alert('Hello, World!');
}
}
methods 내에서 this를 사용해 Vue 인스턴스의 data를 변경할 수 있습니다.
<button @click="increment">숫자 증가</button>
data() {
return {
counter: 0
}
},
methods: {
increment() {
this.counter++;
}
}
하나의 메서드에서 다른 메서드를 호출할 수 있습니다.
methods: {
firstMethod() {
console.log('First method called!');
},
secondMethod() {
this.firstMethod(); // 다른 메서드 호출
}
}
메서드 내부에서 this 키워드를 사용해 Vue 인스턴스의 data, props, computed, 그리고 다른 메서드에 접근할 수 있습니다.
methods: {
updateTitle() {
this.title = 'Updated Title'; // data 속성 변경
}
}
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);
}
}
}
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의 라이프사이클 훅(created, mounted 등)에서도 메서드를 호출하여 컴포넌트 초기화 작업을 할 수 있습니다.
mounted() {
this.fetchData(); // 컴포넌트가 마운트된 후 데이터를 가져옴
}
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>