홍준혁

Vue.js-computed 본문

Vue.js

Vue.js-computed

홍준혁 [Hong-JunHyeok] 2020. 9. 14. 17:05
728x90

Vue에서 간단히 연산을 하는 경우

<!DOCTYPE html>
<html>
    <head>
        <title>Vue.js Sample</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">{{ message.split('').reverse('').join('') }}</div>
        <script>
            new Vue({
                el: "#app",
                data: {
                    message: "안녕하세요",
                },
            });
        </script>
    </body>
</html>

 

이렇게 {{  }}안에 많은 로직이 있으면 보기 흉하고 유지 보수하기 힘들어진다.

※ {{}}안에 내용은 자바스크립트코드가 들어갈 수 있다

 

그래서 나온것이 computed인데 computed를 쓰면 

 

<!DOCTYPE html>
<html>
    <head>
        <title>Vue.js Sample</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">{{ reversedMessage }}</div>
        <script>
            new Vue({
                el: "#app",
                data: {
                    message: "안녕하세요",
                },
                computed: {
                    reversedMessage() {
                        return this.message.split("").reverse("").join("");
                    },
                },
            });
        </script>
    </body>
</html>

 

이렇게 함수화시켜서 간단히 표현할 수 있다.

 

하지만 여기서 의문점이 들것이다. 

methods에다가 함수를 선언하고 하면 결과는 다르지 않을 텐데 왜 굳이 computed에 정의를 했느냐

인데 이것은 computed속성의 특징때문인데. computed는 "미리 계산된"이라는 뜻이다. 

처음에 한번 계산하고 또 한번 쓸 때 전에 계산된 값을 한번 더 사용하게 된다.

 

또한 메시지 값이 바뀌게 된다면 computed는 바뀐 값을 catch 하고 실행하게 된다. 

그래서 

<!DOCTYPE html>
<html>
    <head>
        <title>Vue.js Sample</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <button v-on:click="changeMessage">Click</button>
            <br />{{ reversedMessage }} <br />{{ reversedMessage }} <br />{{
            reversedMessage }}
        </div>
        <script>
            new Vue({
                el: "#app",
                data: {
                    message: "메시지를 거꾸로 했습니다.",
                },
                methods: {
                    changeMessage() {
                        this.message = "메시지가 바뀌었습니다.";
                    },
                },
                computed: {
                    reversedMessage() {
                        return this.message.split("").reverse("").join("");
                    },
                },
            });
        </script>
    </body>
</html>

 

위의 코드처럼 하게 된다면 버튼을 누르면 값이 바뀌고 computed는 값이 바뀐걸 catch 하고 자동으로 값이 바뀌는 모습을 확인할 수 있다.

728x90

'Vue.js' 카테고리의 다른 글

Vue.js 상위-하위 컴포넌트 데이터 전달  (0) 2020.09.21
Vue.js-watch속성  (1) 2020.09.14
Vue.js-폼 입력 바인딩  (1) 2020.09.14
Vue.js-이벤트  (0) 2020.09.14
Vue.js-데이터 바인딩  (0) 2020.09.13
Comments