Uniapp 开发 抽奖应用

266 阅读2分钟

Uniapp是什么

使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码应用多个平台。 uni-app官网 (dcloud.net.cn)

开始使用

1、下载开发工具

HBuilderX下载地址: 下载地址

具体操作可以查看Windows - HBuilderX 文档 (dcloud.net.cn)

2、创建项目

【文件】=>【新建】=>【项目】输入项目名,选择默认模板。

3、运行项目

【运行】=>【运行到内置游览器】

【运行】=>【运行到手机或模拟器】=>【运行到Android App基座】

4、发行项目

【发行】=>【原生App-云打包】

Android(Apk包)=> xxx.yyy.zzz => 使用公共测试证书 => 打正式包 => 快速安心打包 => 打包(如报错,可按提示到网站补充个人信息)

【发行】 => 【网站-PC Web 或 手机 H5】,编译后的文件在 unpackage/dist/build/h5里

5、目录结构

目录结构.png

6、配置页面路由

新建一个Test页面 在pages.json添加配置

{
    "path": "pages/Test/index",
    "style": {
            "navigationBarTitleText": "",
            "enablePullDownRefresh": false
    }
}

7、uniapp与Vue的区别

  • 开发使用Vue单文件组件<template>,<script>,<style>
  • 组件标签<div>换成<view><span>换成<text><a>换成<navigator>
  • 接口能力(JS API) uni.request()
  • 数据绑定及事件处理同 Vue.js,同时补充了App及页面的生命周期
  • 使用flex布局,单位rpx
  • 非H5端 不支持 windowdocumentnavigator等游览器的js API

8、创建项目

新建page,勾选在pages.json中注册,会自动在pages.json添加配置,

 {
    "path": "pages/Setting/Setting",
    "style": {
            "navigationBarTitleText": "设置",
            "enablePullDownRefresh": false
    }
}

配置tabbar

"tabBar": {
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "backgroundColor": "#ffffff",
    "list": [{
            "pagePath": "pages/index/index",//index的路径
            "iconPath": "static/shouye.png",
            "selectedIconPath": "static/shouye-select.png",
            "text": "抽奖"
    
    }, {
            "pagePath": "pages/Setting/Setting",//Setting的路径
            "iconPath": "static/more.png",
            "selectedIconPath": "static/more-select.png",
            "text": "设置"
    }]
}

思路: 获取两数之间的随机数

//(最大数-最小数)+ 最小数
getRandomNum(){
 return this.min + Math.floor(Math.random()*(this.max - this.min))
}
//Math.random()取随机数
//Math.floor()四舍五入向下取数

v-show控制开始和暂停按钮,并添加点击事件,点击开始setInterval计时显示随机数,清除计时则暂停

<template>
	<view class="content">
		<view class="text">
			<text>{{num}}</text>
		</view>
		<view class="button-area">
			<button v-show="isStart" @click="start">开始抽奖</button>
			<button v-show="!isStart" @click="stop">结束抽奖</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				num: 40,
				isStart:true,
				min:0,
				max:100,
				interval:100,
				isOver:true,
				clock:undefined,
			}
		},
		onLoad() {

		},
		methods: {
			start(){
				this.isStart = false 
				this.clock = setInterval(()=>{
					this.num = this.getRandomNum()
				},this.interval)
			},
			stop(){
				clearInterval(this.clock)
				this.isStart = true
			},
			getRandomNum(){
				return Math.floor(this.min + Math.random()*(this.max - this.min))
			}
			
		}
	}
</script>

用户可以自定义max,min,interval;三个input用v-model双向绑定数据;保存按钮绑定事件,将数据保存在本地uni.setStorageSync,添加钩子初始化保存的数据uni.getStorageSync

<template>
	<view class="content">
		<view class="list">
			<view class="uni-form-item uni-column">
				<view class="title">最大值</view>
				<input class="uni-input" v-model="max" type="number" placeholder="最大值" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">最小值</view>
				<input class="uni-input" v-model="min" type="number" placeholder="最小值" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">时间间隔(ms)</view>
				<input class="uni-input" v-model="interval" type="number" placeholder="时间间隔" />
			</view>
		</view>
		<view class="button-area">
			<button @click="onSave">保存</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				min: 0,
				max: 100,
				interval: 100,
			}
		},
		created(){
			let setting = uni.getStorageSync('setting') || 
			{min: 0,max: 100, interval: 100,}
			this.max = setting.max
			this.min = setting.min
			this.interval = setting.interval
		},
		methods: {
			onSave() {
				let setting = {
					max: this.max,
					min: this.min,
					interval: this.interval
				}
				uni.setStorageSync('setting', setting)
			}
			
		}
	}
</script>

将保存好的数据运用在index页面,onShow每次刷新,获取本地的数据

onShow(){
    let setting = uni.getStorageSync('setting') || 
    {min: 0,max: 100, interval: 100,}
    this.max = setting.max
    this.min = setting.min
    this.interval = setting.interval
},
getRandomNum(){
	return Math.floor(parseInt(this.min) + Math.random()*(parseInt(this.max) - parseInt(this.min)))
}

本第获取的是字符串,parseInt转换成数字

UniCloud上线

官方解释:是为开发者提供的基于serverless模式和js编程的云开发平台(serverless:已经搭建好的后端)

可参考UniCloud

创建云服务

unicloud.dcloud.net.cn后台登录 【创建服务空间】=>【云数据库】=>【创建数据库表schema】=>【其他】【用户】

屏幕截图 2022-11-26 135212.png 创建一个我们需要的 数据库 创建空表

屏幕截图 2022-11-26 135212.png

回到 HBuilderX

给创建好的项目绑定uniCloud数据后台,下载所有云函数、公共模块及actions,下载所有DB Schema及扩展校验函数,修改了数据需要及时上传。

schema2code代码生成

添加上传图片的组件

在lettory数据添加表结构


"photo": {
        "bsonType": "file",
        "title": "图片",
        "fileMediaType": "image", // 可选值 all|image|video 默认值为all,表示所有文件,image表示图片类型文件,video表示视频类型文件
        "fileExtName": "jpg,png", // 扩展名过滤,多个用 , 分割
      }

schema2code代码生成

实现随机图片

还是实现两个数之间的随机数,数的范围就是数据库里数据的长度,产生的随机数和数据库里的index一致,则添加选中元素样式

<template>
	<view class="content">
		<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, hasMore, error}" :collection="collectionList"
			field="title,photo">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="data">
				<uni-list class="list">
					<uni-list-item v-for="(item, index) in data" :key="index" :class="{active: index === number}">
						<template v-slot:body>
							<view class="item">
								<text>
									<image :src="item.photo.url" mode="aspectFit" />
								</text>
								<text>{{item.title}}</text>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</unicloud-db>

		<view class="button-area">
			<button v-show="isStart" @click="start">开始抽奖</button>
			<button v-show="!isStart" @click="stop">结束抽奖</button>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();//获取数据库实例
	const dbCollectionName = 'lottery';

	export default {
		data() {
			return {
				number: 0,
				max: 0,
				interval: 100,
				isStart: true,
				clock: null,
				collectionList: dbCollectionName,
				length: 0,
				
			}
		},
		created() {
			this.$nextTick(() => {
				db.collection(dbCollectionName)
					.get()//获取数据
					.then((res) => {
						// res 为数据库查询结果
						this.max = res.result.data.length;
					})
			})
		},
		onPullDownRefresh() {
			this.$refs.udb.loadData({
				clear: true
			}, () => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			this.$refs.udb.loadMore()
		},
		methods: {
			start() {
				this.isStart = false
				this.clock = setInterval(() => {
					this.number = this.getRandomNum()
				}, this.interval)
			},
			stop() {
				clearInterval(this.clock)
				this.isStart = true
			},
			getRandomNum() {
				return Math.floor(Math.random() * parseInt(this.max))
			},
		}
	}
</script>