1. 猜数字游戏
1.1 HTML
<body>
<div id="d1" >
<h1>猜数游戏</h1>
<h2>请输入一个0-99之间的随机整数</h2>
<input type="text" style="font-size: 20px;" ref="getNum"> <button @click="m1()" >提交</button> <button @click="m4()">开始</button>
<div id="d2">
结果:<span id="r1">{{txt}}</span>
<br>
当前还可以猜测次数:<span>{{times}}</span>
</div>
</div>
</body>
<script src="../vuejs/vue.js"></script>
1. 2CSS
#d1{
margin: auto;
padding: 0%;
text-align: center;
width: 400px;
}
#d2{
text-align: left;
font-size: 20px;
}
button:hover,button:active{
box-shadow: 1px 1px 1px 1px gray;
border: 1px solid;
}
1.3 Vue.js
new Vue({
el:"div",
data:{
times: 10,
num: -1,
target: 100,
txt: "请点击开始"
},
methods:{
// 获取数值
m1 : function(){
// 通过ref来获取
var n = this.$refs.getNum.value
console.log(n)
if(this.target == 100){
alert("你还没有点开始")
this.$refs.getNum.value = ""
return;
}
var t1 = /^[0-9]{1,2}$/
if(!t1.test(n)) {
alert("输入无效")
this.$refs.getNum.value = ""
}else{
if(this.m3()){// 答对了再输入不响应
this.$refs.getNum.value = ""
alert("你已经答对了")
return;
}
if(!this.m2()){// 次数超了再输入不响应
this.$refs.getNum.value = ""
return;
}
// 接收到数字
this.num = n
this.$refs.getNum.value = ""
this.m3()// 比较
}
},
// 判断次数
m2 : function(){
if(this.times == 0){
alert("游戏结束")
this.txt = "你输了"
return false;
}
this.times--
return true
},
// 判断大小
m3 : function(){
if(this.num > this.target){
this.txt = "你猜大了"
}
if(this.num < this.target){
this.txt = "你猜小了"
}
if(this.num == this.target){
this.txt = "你猜对了!答案是:" + this.target
return true
}
return false
},
// 重新开始
m4 : function(){
this.times = 10
this.txt = "请开始猜数"
this.num = -1
this.target = parseInt(Math.random() * 100)
this.$refs.getNum.value = ""
console.log("答案是:"+ this.target)
}
}
})
1.4 效果
2 反转内容修改样式
<!--
<div class="pre">内容为: XX</div>
<div class=" after">反转后内容为: XX</div>
<div class="total">反转前内容为XX,反转后内容为xx</div>
---------------------------------------------------------------
(1) 用data给页面初始内容赋值“你好,欢迎学习vue”。
(2) 用方法实现字符串反转,显示结果为“euv习学迎欢,好你”。
(3) 用方法给div都加上相同的颜色,原来有的class要保留。s
(4) 用v-bind给第二个div再加一一个字体为20px。
-->
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.pre{
color: #ff6666;
}
.after{
color: slateblue;
}
</style>
</head>
<body>
<div id="app" v-bind:style="{color:m2()} ">
<div class="pre">内容为: {{x1}}</div> <!-- 修改字体大小 -->
<div class="after" v-on="m1()" v-bind:style="{fontSize: size + 'px' }">反转后内容为: {{x2}}</div>
<div class="total">反转前内容为{{x1}},反转后内容为{{x2}}</div>
</div>
<script src="../vuejs/vue.js"></script>
<script>
var vm = new Vue({
el:"div",
data:{
num: 0,
x1:"你好,欢迎学习vue",
x2: "",
color: "green",
size: 20
},
methods:{
// 反转字符串
m1: function(){
this.x2 = this.x1.split("").reverse().join("")
},
// 加颜色
m2: function(){
return this.color
}
}
})
</script>
</body>