728x90

methods, computed, watch에 대해 알아보겠습니다.

 

methods는 호출하는 경우에만 로직이 실행되며

computed의 경우 데이터의 값이 변경되면 알아서 자동적으로 실행되어 주는 차이가 있습니다.

computed는 연산 결과를 캐싱(보관)하고 있다. 쓰는 경우에 가져다 쓸 수 있어 복잡한 연산에 특화 되어있다 생각하시면 됩니다.

 

watch의 경우는 데이터의 변화를 감지하고 특정 로직을 수행하는데 computed와 다르게 비동기 처리(웹 통신 등)에 적합합니다.

 

아래는 전체 코드입니다.

<!DOCTYPE html>
<html lang="en">
<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>Method Computed Watch</title>
</head>
<body>
    <div id="app">
        <div>{{ method_message }}</div>
        <div>{{ computedMessage }}</div>
        <button v-on:click="methodsMessage">click me!</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js "></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                method_message: 'Method Test Msg',
                computed_message: 'Computed Test Msg',
            },
            methods: {
                methodsMessage: function () {
                    this.method_message = this.method_message.split(' ').reverse().join(' ');
                },
            },
            computed: {
                computedMessage: function () {
                    return this.computed_message.split(' ').reverse().join(' ');
                },
            },
            watch: {
                method_message: function (newMsg, oldMsg) {
                    console.log('Old Msg:', oldMsg, ' / New Msg:', newMsg);
                },
            },
        });
    </script>
</body>
</html>

버튼을 클릭할 때 마다 methods의 methodsMessage()를 호출해서 변환시켜 줍니다.

computed는 처음 열었을 때 변환 한번이 이루어 지고

watch에는 method_message를 등록하여 이전과 현재 변화된 결과를 가져와 출력하게 만들었습니다.

 

아래와 같이 출력되는 것을 확인하실 수 있습니다.

 

이렇게 methods, computed, watch를 사용해 보았습니다.

+ Recent posts