2. 请使用uniapp实现比较数字大小。如图所示,有两个输入框,可以输入数字,输入后单击“比较”按钮,会在按钮的下方显示比较结果,有“第1个数大”、“第2个数大”和“两数相等”这3种情况。(注:其中input组件可以实时监听input值的事件是@input)
时间: 2023-11-27 19:50:58 浏览: 337
首先需要创建一个uniapp项目,然后在pages文件夹下创建一个新的页面,命名为compare。
在compare.vue中,我们需要添加两个input组件和一个button组件,如下所示:
```
<template>
<view class="container">
<view class="input-container">
<input type="number" placeholder="请输入第一个数字" @input="handleInput1" />
</view>
<view class="input-container">
<input type="number" placeholder="请输入第二个数字" @input="handleInput2" />
</view>
<view class="btn-container">
<button type="primary" size="default" @click="compare">比较</button>
</view>
<view class="result-container">{{result}}</view>
</view>
</template>
<script>
export default {
data() {
return {
num1: null,
num2: null,
result: "",
};
},
methods: {
handleInput1(e) {
this.num1 = e.target.value;
},
handleInput2(e) {
this.num2 = e.target.value;
},
compare() {
if (this.num1 > this.num2) {
this.result = "第1个数大";
} else if (this.num1 < this.num2) {
this.result = "第2个数大";
} else {
this.result = "两数相等";
}
},
},
};
</script>
<style scoped>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
}
.input-container {
margin: 20px;
}
.btn-container {
margin-top: 40px;
}
.result-container {
margin-top: 40px;
font-size: 20px;
}
</style>
```
在data中我们定义了num1、num2和result三个变量,分别表示输入的第一个数字、第二个数字和比较结果。在methods中我们定义了handleInput1、handleInput2和compare三个方法,分别用于监听输入框的输入事件、比较按钮的点击事件和比较两个数字的大小。
在handleInput1和handleInput2方法中,我们使用event.target.value获取input框中的值,并将其赋值给num1和num2变量。
在compare方法中,我们使用if...else语句判断num1和num2的大小关系,并将结果赋值给result变量。
最后在template中,我们将输入框、按钮和比较结果都进行了渲染。
这样我们就完成了比较数字大小的功能。可以通过运行uniapp项目,打开compare页面,输入两个数字并点击比较按钮来测试。