vue示例demo02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue-v2.0.js"></script>
    <link href="//cdn.bootcss.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet">
    <style>
        input {
            text-indent: 10px;
        }

    </style>
</head>
<body>
<div class="container">
    <div class="game">
        <div class="question">
            <label>
                Ask a yes/no question: <input type="text" v-model="question" placeholder="it must contains '?'">
            </label>
        </div>
        <div class="answer">
            {{answer}}
        </div>
        <div>
            <img :src="img_res" alt="">
        </div>
    </div>

</div>


</body>
<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>
<script src="//cdn.bootcss.com/vue/2.1.10/vue.js"></script>
<script>


    new Vue({
        el: '.game',
        data: {
            img_res: '',
            question: '',
            answer: 'I cannot give you an answer until you ask a question!'
        },
        methods: {
            getAnswer: _.debounce(function (val) {
                var vm= this;
                if (val.indexOf('?') == -1) {
                    this.answer = 'Questions usually contain a question mark. ;-)';
                    return;
                }
                this.answer = 'Thinking...';
                axios.get('https://yesno.wtf/api')
                        .then(function (response) {
                            vm.answer = _.capitalize(response.data.answer);
                            vm.img_res = response.data.image;
                        })
                        .catch(function (error) {
                            vm.answer = 'Error! Could not reach the API. ' + error
                        });
            },500)
        },
        watch: {
            question: function (val) {
                this.answer = 'Waiting for you to stop typing...';
                this.getAnswer(val);
            }
        }
    })
</script>
</html>
View Code

 

posted @ 2017-02-23 15:39  _白马非马  阅读(141)  评论(0编辑  收藏  举报