자바 공부/[자바] 기본 공부

[Vue.js] Methods, computed, watch

햅2024 2024. 12. 3. 21:33

methods, computed, watch

  • methods : 실행할 때마다 실행되는 함수 모음
  • computed : 변수의 값이 변하지 않으면 다시 실행하지 않고 caching된 값을 그대로 리턴
  • watch : 특정한 변수의 값이 변경되는지 모니터링 
<!DOCTYPE html>
<html>
<head>
    <title>Watch Example</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.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>
    <h1>Watch를 통한 무슨 질문이든 받기 </h1>
    <hr>
    <h2>Yes/No로 대답할 수 있는 질문을 해보십시오</h2>
    <div id="watch-ex">
        <p><input type="text" v-model="question"></p> <!--question과 양방향 바인딩-->
        <p>{{ answer }}</p>
    </div>
</body>
<script>
    var Qapp = new Vue({
        el:'#watch-ex',
        data:{
            question: '',
            answer: '물어보세요'
        },
        created: function(){
            console.log("Created OK");
            //_.debounce(func, wait, [options])
            //하단 methods의 getAnswer로 정의한 함수를 0.5초마다 실행함
            this.debouncedGetAnswer = _.debounce(this.getAnswer, 500);
        },
        methods: {
            getAnswer: function(){
                if(this.question.indexOf('?') == -1){ //질문이 물음표로 끝나는가
                    this.answer = '?로 끝나야 대답합니다.';
                    return;
                }
                this.answer = '조금만 기다리세요';
                var vm = this;
                axios.get('https://yesno.wtf/api')
                     .then(function(response){
                        vm.answer = response.data.answer;
                     })
                     .catch(function(error){
                        vm.answer = '오류입니다'
                     });
            }
        },
        watch: {
            // 질문 변경 시마다 이 부분이 실행됨
            // 질문을 모니터링 하기 위해 question 을 살펴보다 실행
            question: function(){
                console.log("질문 바뀐 것 감지");
                this.answer = "열심히 입력하고 계시는군요";
                this.debouncedGetAnswer(); 
            }
        }
    });
</script>
</html>

'자바 공부 > [자바] 기본 공부' 카테고리의 다른 글

[Vue.js] form 요소 활용하기  (2) 2024.12.04
[Vue.js] class 속성 변경하기  (0) 2024.12.04
[Vue.js] Componenet  (2) 2024.12.03
[Vue.js] v-문법  (0) 2024.11.28
[Node.js 2일차] http 모듈  (2) 2024.11.28