完整demo
<html>
<head>
<title>组件注册+开奖小游戏</title>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<button @click="start">开奖</button>
<my-button :n="randoms[0]"></my-button>
<my-button :n="randoms[1]"></my-button>
<my-button :n="randoms[2]"></my-button>
<span style="color:red">{{message}}</span>
</div>
</body>
<script>
//全局组件注册,注册前,请保证其在根vue实例(root vue instance)实例化之前完成注册
Vue.component('my-button', {
//组件模板 自定义button标签,button内容绑定属性n,本案例中表示一个随机数
template: '<button>{{ n }}</button>',
//来个属性
props: ['n']
})
//获取指定区间范围内的随机数,包括lowerValue和upperValue
function randomFrom(lowerValue, upperValue) {
return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
}
var app = new Vue({
el: '#app',
data: {
randoms: [],
message:''
},
methods: {
start: function () {
//每次进来的时候,置空randoms和message,模拟重新开奖
this.randoms = []
this.message = ''
//构造3个随机数【随机数可以一样,也可以不一样,具体业务具体对待】
while (true) {
var isExists = false;
// 获取一个1–3范围的数
var random = parseInt(randomFrom(1,3))
this.randoms.push(random);
// 如果有3位随机数了,终止循环
if (this.randoms.length === 3)
break;
}
//循环判断 是否中大奖了
var isBinGo = true;
var n = this.randoms[0]
//拿第一个元素依次和其后面的元素进行比较
for(var i=1;i<this.randoms.length;i++){
if(n !== this.randoms[i]){
isBinGo = false;
break;
}
}
if(isBinGo){
this.message ='恭喜你,中大奖了!!!'
}
}
}
})
</script>
</html>
一、产生指定范围内的随机数(方法)
二、开奖事件绑定 +组件复用+DOM数据渲染
(1)DOM
(2)my-button组件注册
(3)数据渲染
三、效果演示