<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue2</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>methods</h1>
<p>{{changeMessage()}}</p>
<p>{{changeMessage()}}</p>
<p>{{changeMessage()}}</p>
<p>{{changeMessage()}}</p>
<p>{{changeMessage()}}</p>
<p>{{changeMessage()}}</p>
<div>{{text}}</div>
</div>
<script>
new Vue({
el: '#app',
data: {
text: '메서드를 실행해 보자',
},
methods: {
changeMessage(){
console.log('메서드 실행 완료')
this.text = '메서드 실행 완료';
},
},
})
</script>
</body>
</html>
실행결과
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue2</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>computed</h1>
<p>{{computedTest}}</p>
<p>{{computedTest}}</p>
<p>{{computedTest}}</p>
<p>{{computedTest}}</p>
<p>{{computedTest}}</p>
<p>{{computedTest}}</p>
<p>{{computedTest}}</p>
<div>{{text2}}</div>
</div>
<script>
new Vue({
el: '#app',
data: {
text2: '컴퓨티드를 실행해 보자'
},
computed: {
computedTest(){
console.log('컴퓨티드 실행 완료')
this.text2 = '컴퓨티드 실행 완료'
}
},
})
</script>
</body>
</html>
실행결과
버튼을 클릭하면 메시지를 변경하고 watch가 변경된 메시지의 문자열을 거꾸로 만드는 코드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue2</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div>변경 전 : {{message}}</div>
<div>변경 후 : {{changeMessage}}</div>
<button @click="clickEvent">클릭</button>
</div>
<script>
new Vue({
el: '#app',
data:{
message: 'Hello',
changeMessage: ''
},
methods: {
clickEvent(){
this.message = 'javascript'
}
},
watch:{
message :function(newVal, oldVal){
console.log('newVal : ' + newVal + ' oldVal : ' + oldVal);
this.changeMessage = newVal.split('').reverse('').join('');
},
},
})
</script>
</body>
</html>
실행결과