Home  >  Article  >  Web Front-end  >  How does the vue component implement the number guessing function?

How does the vue component implement the number guessing function?

php中世界最好的语言
php中世界最好的语言Original
2018-04-16 09:15:551972browse

This time I will show you how the vue component can implement the number guessing function. What are the precautions for the vue component to implement the number guessing function. The following is a practical case, let's take a look.

<!doctype html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>vue组件猜数字游戏</title>
  <script src="js/vue.js"></script>
 </head>
 <body>
 <p id="container">
    <p>{{msg}}</p>
    <my-game></my-game>
  </p>
  <script>
  /*
  *创建一个组件,my-game:
   猜数字大小。
   组件:一个input和一个p构成
   当组件准备挂载的时候,初始化一个随机数,
   在input取输入的时候,
   如果输入的数字小了,在p显示:输入的太小了;
   如果输入的数字大了,在p显示:输入的太大了;
   否则就提示输入正确。
  * */
  //完成组件的创建
    Vue.component("my-game",{
      data:function(){
        return {
          randomNum:0,
          myInput:0,
          result:""
        }
      },
      template:`
        <p>
          <input type="text" v-model.number="myInput"/>
          <br>
          <p>{{result}}</p>
        </p>
      `,
      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>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use the vue component life cycle

The implementation principle of JSONP

What is the difference between using js string indexof and search

The above is the detailed content of How does the vue component implement the number guessing function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn