Uniapp随机选餐功能实现:解决选择困难症
<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>
<p>使用Uniapp开发一个简单的随机选餐小程序,帮助用户快速决定今天吃什么,解决选择困难症。只需点击“选择”按钮,即可随机获得推荐菜品。</p>
<p><strong>实现步骤:</strong></p>
<ol>
<li>创建一个uniapp项目,命名为'what-to-eat'。</li>
<li>在pages文件夹下创建一个'index'页面。</li>
<li>在index.vue文件中,添加一个'选择'按钮和一个'展示'文本框。</li>
<li>在data中定义一个'foods'数组,存放各种可以选择的食物。</li>
<li>在methods中添加一个'chooseFood'方法,用于随机选取一个食物。</li>
<li>在'选择'按钮的@click事件中调用'chooseFood'方法,并将结果赋值给'展示'文本框。</li>
<li>在页面中添加样式,美化界面。</li>
</ol>
<p><strong>代码示例:</strong></p>
<pre><code class="language-vue"><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>
</code></pre>
<p>以上代码实现了一个简单的随机选餐功能,用户每次点击“选择”按钮,就会随机选取一个食物并展示在页面上。用户可以根据展示的结果决定今天吃什么,从而避免了选择困难症。</p>
原文地址: https://www.cveoy.top/t/topic/mCuh 著作权归作者所有。请勿转载和采集!