Home > Web Front-end > JS Tutorial > Detailed example of implementing a guessing game based on vue components

Detailed example of implementing a guessing game based on vue components

小云云
Release: 2017-12-26 14:08:04
Original
2692 people have browsed it

This article mainly introduces the guessing game based on vue components in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

The example in this article shares the specific code of the vue number guessing game for your reference. The specific content is as follows


##

<!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>
Copy after login

Related recommendations:

How to write a ejection ball in the vue component

Example of the method of using iframe elements in the vue component

Vue component Options props

The above is the detailed content of Detailed example of implementing a guessing game based on vue components. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template