2024-03-08
2024-03-07 本文已影响0人
KenChen_939
<template>
<view class="content">
<!-- 用一个view包裹三个图片组件,图片组件的图片地址使用响应式数据,即data中的数据 ,为避免
重复样式代码,image组件都用了一个class,用来设置间距-->
<view style="display: flex;flex-direction: row;">
<image class="imgMargin" :src="imagePathOne"></image>
<image class="imgMargin" :src="imagePathTwo"></image>
<image class="imgMargin" :src="imagePathThree"></image>
</view>
<!-- view包裹的按钮,两个按钮纵向排列并居中 -->
<view class="text-area"
style="display: flex;flex-direction: column; align-items: center;align-content: center;">
<button style="margin-top: 20px;" @click="test()">点击抽牌</button>
<button style="margin-top: 20px;" @click="test2()">停止抽牌</button>
</view>
</view>
</template>
<script>
export default {
//响应式数据在这里定义,数据变化则页面变化
data() {
return {
mytimer:{},
title: 'Hello Uniapp!',
imagePathOne:"",
imagePathTwo:"",
imagePathThree:"",
pathList:["/static/a.jpg","/static/b.jpg","/static/c.jpg"]
}
},
onLoad() {
},
methods: {
//停止抽牌方法,清除定时器
test2(){
clearInterval(this.mytimer)
},
//开始抽牌方法
test(){
//定义该变量是为了方便函数内部访问外部对象
const that = this
//定义了一个定时器并交给vue进行管理,mytimer对象方便停止按钮方法清除定时器
this.mytimer =setInterval(function(){
//获取三个0-2的随机数
let a = that.randomNum(0,2)
let b = that.randomNum(0,2)
let c = that.randomNum(0,2)
//将随机获取的图片地址赋值给图片组件的data对象
that.imagePathOne = that.pathList[a]
that.imagePathTwo= that.pathList[b]
that.imagePathThree= that.pathList[c]
//打印每次随机数的值
console.log(a+'-'+b+'-'+c)
},900)//每900毫秒执行一次
},
//获取随机数方法,min参数和max参数的意思是获取x至x之间的随机数
randomNum(minNum,maxNum){
switch(arguments.length){
case 1:
return parseInt(Math.random()*minNum+1,10);
break;
case 2:
return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
break;
default:
return 0;
break;
}
}
},
//创建阶段生命周期,为三个图片组件设置一个基础图片,即扑克牌的背面
created() {
// this.title = "创建阶段"
this.imagePathOne = "/static/logo.png"
this.imagePathTwo= "/static/logo.png"
this.imagePathThree= "/static/logo.png"
},
mounted() {
// this.title = "挂载阶段"
},
updated() {
// this.title = "更新阶段"
},
destroyed() {
// this.title = "销毁阶段"
}
}
</script>
<style>
/* 自定义的class,image组件使用,定义了间距和最大宽度和最大高度 */
.imgMargin{
margin: 8px;
max-width: 100px;
max-height: 200px;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>