用uniapp写一个随机选则今天吃什么的功能
- 创建一个uniapp项目,命名为“what-to-eat”。
- 在pages文件夹下创建一个“index”页面。
- 在index.vue文件中,添加一个“选择”按钮和一个“展示”文本框。
- 在data中定义一个“foods”数组,存放各种可以选择的食物。
- 在methods中添加一个“chooseFood”方法,用于随机选取一个食物。
- 在“选择”按钮的@click事件中调用“chooseFood”方法,并将结果赋值给“展示”文本框。
- 在页面中添加样式,美化界面。
代码如下:
<template>
<view class="container">
<view class="header">今天吃什么?</view>
<view class="content">
<view class="button" @click="chooseFood">选择</view>
<view class="result">{{ food }}</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
foods: ["炒饭", "盖浇饭", "面条", "饺子", "火锅", "烧烤", "披萨", "汉堡", "寿司"],
food: ""
};
},
methods: {
chooseFood() {
const index = Math.floor(Math.random() * this.foods.length);
this.food = this.foods[index];
}
}
};
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.header {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
}
.button {
padding: 10px 20px;
background-color: #409eff;
border-radius: 5px;
color: #fff;
font-size: 16px;
cursor: pointer;
margin-bottom: 20px;
}
.result {
font-size: 24px;
font-weight: bold;
text-align: center;
}
</style>
以上代码实现了一个简单的随机选餐功能,用户每次点击“选择”按钮,就会随机选取一个食物并展示在页面上。用户可以根据展示的结果决定今天吃什么,从而避免了选择困难症。
原文地址: https://www.cveoy.top/t/topic/bb4W 著作权归作者所有。请勿转载和采集!