Vue

Vue.js methods, computed, watch

테라시아 2025. 1. 12. 22:59

methods, computed, watch
    methods : 실행할 때마다 실행되는 함수 모음
    computed : 변수의 값이 변하지 않으면 다시 실행하지 않고
               caching된 값을 그대로 리턴
    watch : 특정한 변수의 값이 변경되는지 모니터링

 

☆ Code

<!doctype html>
<html>
<head>
    <title>Watch Example</title>
</head>
<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>
<body>
    <h1>Watch를 통한 무슨 질문이든 받기</h1>   
    <hr>
    <h2>Yes/No로 대답할 수 있는 질문을 해보십시오.</h2>
    <div id="watch-ex">
        <p><input type="text" v-model="question"></p>
        <p>{{ answer }}</p>
    </div>
</body>
<script>
    var Qapp = new Vue({
        el: '#watch-ex',
        data: {
            question: '',
            answer: '물어봐야 답을하죠'
        },
        created: function(){
            console.log("Created OK");
            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: function(){
                console.log("질문바뀐것 감지");
                this.answer = "열심히 입력하고 계시는군요";
                this.debouncedGetAnswer();
            }
        }
    });
</script>
</html>

'Vue' 카테고리의 다른 글

Vue.js form  (0) 2025.01.14
Vue.js class  (0) 2025.01.13
Vue.js Component  (0) 2025.01.11
Vue.js Model  (0) 2025.01.10
Vue.js 기초문법  (0) 2025.01.08