vue猜数字游戏

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>vue组件猜数字游戏</title>
    <script src="js/vue.js"></script>
 </head>
 <body>
  <div id="container">
        <p>{{msg}}</p>
        <my-game></my-game>
    </div>
    <script>
    /*
    *创建一个组件,my-game:
     猜数字大小。
     组件:一个input和一个p构成
     当组件准备挂载的时候,初始化一个随机数,
     在input取输入的时候,
     如果输入的数字小了,在p显示:输入的太小了;
     如果输入的数字大了,在p显示:输入的太大了;
     否则就提示输入正确。
    * */

    //完成组件的创建
        Vue.component("my-game",{
            data:function(){
                return {
                    randomNum:0,
                    myInput:0,
                    result:""
                }
            },
            template:`
                <div>
                    <input type="text" v-model.number="myInput"/>
                    <br>
                    <p>{{result}}</p>
                </div>
            `,
            beforeMount: function () {
        //创建一个100以内的随机的整数
        var num = Math.floor(Math.random()*100);
        console.log(num);
        this.randomNum = num;
        },
            //当数据改变时执行的操作
            watch:{
                myInput:function(){
                    if(this.myInput==this.randomNum){
                        this.result = "恭喜:猜对了";
                    }else if(this.myInput>this.randomNum){
                        this.result = "啊哦!猜大了";
                    }else{
                        this.result = "啊哦!猜小了";
                    }
                }
            }
        })
        new Vue({
            el:"#container",
            data:{
                msg:"Hello VueJs"
            }
        })
    </script>
 </body>
</html>
原文地址:https://www.cnblogs.com/wangruifang/p/7768378.html