Vuejs2 기초 - [복습]methods, computed, watch

riverkim·2022년 8월 30일
0
post-thumbnail

[복습] methods, computed, watch

methods

  • method를 사용하려고 할 때 마다 계산
  • 랜더링 할때마다 항상 method를 호출
<!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>

실행결과


computed

  • Vue 인스턴스가 생성될 때, data의 값을 받아 미리 계산하여 저장하고 불러옴(캐싱)
  • method 형태로 작성하지만 Vue에서 proxy 처리하여 property 처럼 사용
  • 특정 데이터의 변경사항을 실시간으로 처리
  • 호출시에도 method 가 아닌 property 와 같이 호출
<!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

  • Vue Instance의 특정 property가 변경될 때 실행할 콜백 함수를 설정
  • watch는 data가 변경되었을 경우 다른 data를 변경하는 등의 작업에 사용

버튼을 클릭하면 메시지를 변경하고 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>

실행결과

profile
Hello!

0개의 댓글