반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
    </head>
    <body>
        <div id = "app">
            <input type="text" v-model ="message">
            <span v-if = "message != ''">{{ message }} -> {{ msg }}</span>
        </div>
 
        <script>
            var vm = new Vue({
                el : '#app',
                data :{
                    message : ""
                },
                computed:{
                    msg : function(){
                        return this.message.split('').reverse().join('');
                    }
                }
            })
        </script>
    </body>
</html>
cs


computed 속성을 사용한 팰린드롬 생성기


computed는 javascript의 window.onload와 같은 역할을 한다. 페이지 모든 요소들이 호출 된 후에 computed가 실행되어 계산된다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
    </head>
    <body>
        <div id = "app">
            <p>캐싱된 시간 : {{ now }}</p>
            <p ref ="tester"> input console vm.show() </p> 
        </div>
 
        <script>
            var vm = new Vue({
                el : '#app',
                computed:{
                    now : function(){
                        return Date(Date.now());
                        // return  setInterval(function () { Date(Date.now()) }, 1000);
                    }
                },
 
                methods:{
                    show : function(){
                        tester = this.$refs.tester;
                        setInterval(function () {tester.innerHTML = Date(Date.now()) }, 1000);
                    }
                }
            })
        </script>
    </body>
</html>
cs


캐싱을 사용하는 예 및 method에서 setInterval 이용


computed를 통해 캐싱을 할 수 있고 빠르게 작업을 수행 할 수 있다.


여기서 computed를 이용하고 싶지 않다면 methods의 show func를 이용하여 나타낼 수 있다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
    </head>
    <body>
        <div id = "app">
            {{ fullName }}
        </div>
 
        <script>
            var vm = new Vue({
                el : '#app',
                data:{
                    firstName : 'Foo',
                    lastName : 'Bar'
                },
 
                computed:{
                    fullName:{
                        get: function(){
                            return this.firstName + ' ' + this.lastName
                        },
 
                        set: function(newValue){
                            var names = newValue.split(' ')
                            this.firstName = names[0];
                            this.lastName = names[names.length - 1];
                        }
                    }
                }
            })
        </script>
    </body>
</html>
 
cs


get, set을 이용하여 computed에서 나타낼 수 있다.


getter 를 통해 종속성을 추적하고, setter 를 통해 변경을 알리게 된다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
    </head>
    <body>
        <div id = "app">
            <input type="text" v-model = "first" placeholder="First name">
            <input type="text" v-model = "last" placeholder="Last name">
            <span> {{ fullName }} </span>
            <br>
            <p>first :: {{ first }} </p>
            <p>last :: {{ last }} </p> 
        </div>
 
        <script>
            var vm = new Vue({
                el : '#app',
                data:{
                    first : '',
                    last : '',
                    fullName : ''
                },
                watch:{
                    first :function(val){
                        this.fullName = val + ' ' + this.last;
                    },
                    last : function(val){
                        this.fullName = this.first + ' ' + val;
                    }
 
                    
                }
            })
        </script>
    </body>
</html>
cs



watch를 통해 input text를 다룰 수 있다.


input 폼 부분에서 v-model로 데이터를 감시하고 watch를 통해 fullname 데이터에 값을 반영해준다.


watch는 data부분에 있는 변수명을 그대로 따르면 된다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
        <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
        <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
    </head>
    <body>
        <div id = "qna">
            <p>
                입력창에 질문을 하면 yes or no를 대답해줍니다.
                <input type = "text" v-model = "question">
            </p>
 
            <p> {{ answer }} </p>
        </div>
 
        <script>
            var vm = new Vue({
                el: '#qna',
                data:{
                    question: '',
                    answer: '질문을 하기 전까지는 대답을 할 수 없습니다.' 
                },
                watch:{
                    question : function(newQuestion){
                        this.answer = "입력을 기다리는 중..."
                        this.getAnswer()
                    }
                },
 
                methods:{
                    getAnswer : _.debounce(
                        function(){
                            if(this.question.indexOf('?'=== -1){
                                this.answer = "질문 후에는 ?를 포함해야 합니다."
                                return;
                            }
                            this.answer = "생각중..."
 
                            axios.get('https://yesno.wtf/api')
                                .then(function (response){
                                    vm.$data.answer = _.capitalize(response.data.answer) // or vm.answer
                                })
                                .catch(function (e){
                                    vm.$data.answer = '값에 문제가 있습니다. 다시 시도해 주세요. ' + e
                                })
                        },
 
                        500
                    )
                }
            })
 
        </script>
    </body>
</html>
 
cs


watch를 이용한 감시자 예제


watch에서 question의 값이 변경되는지 확인하고 getAnswer에서 만약 ?가 없다면 '질문 후에는 ~~ 합니다.'를 리턴하고


그게 아니라면 axios를 통해 get를 하여 값을 출력한다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
    </head>
    <body>
        <div id = "app">
            <span> {{ a }} </span>
        </div>
 
        <script>
            function cb(new_val, old_val){
                console.log("new :: %s", new_val);
                console.log("old :: %s", old_val);
            }
 
            var vm = new Vue({
                el : '#app',
                data : {
                    a : 1
                }
            });
 
            var watcher = vm.$watch('a',cb);
 
        </script>
    </body>
</html>
cs



watch기능 인스턴스 밖에서 설정이 가능하다.


위의 내용처럼 watcher = vm.$watch('a',cb) 즉, a의 데이터를 cb 함수로 다루겠다고 명시할 수 있다.









반응형