关于HarmonyOS 2.0相关应用软件的安装和使用可以参考鸿蒙初体验:从安装到第一个程序 Hello HarmonyOS
关于HarmonyOS 2.0JS FA应用的开发和结构可以参考鸿蒙初体验(二):使用JS FA应用的chart组件画一个简单线性图
一、创建项目
首先我们打开DevEco Studio新建一个Js项目
二、编写代码
1.第一种写法:通过input组件的事件change去监听输入的值进行比较
index.css
.container {
flex-direction:column;
width: 100%;
height: 100%;
}
index.hml
<div class ="container">
<text class="text">猜数字</text>
<text>请输入1到100的实数:</text>
<input type="text" name="number" id="number" @change="guess"></input>
</div>
index.js
import prompt from '@system.prompt';
export default {
data(){
return {
ran: parseInt(Math.random()*100)
}
},
guess(num){
var number = num.text;
if (number < 0 || number > 100) {
prompt.showToast({
message: '请输入1到100的实数',
duration: 2000,
});
} else if (this.ran == number) {
prompt.showToast({
message: '恭喜你猜对了,你猜的数字是' + this.ran,
duration: 2000,
});
} else if (this.ran > number) {
prompt.showToast({
message: '很遗憾,你猜小了',
duration: 2000,
});
} else if (this.ran < number) {
prompt.showToast({
message: '很遗憾,你猜大了',
duration: 2000,
});
}
}
}
效果图:
这种每一次输入就会提示一下,不推荐使用,这里只是试一下change事件,我觉得输入完成后使用手动点击校验更好一点,那么就使用下面这种写法。
2.第二种写法:通过绑定value点击事件进行比较
index.css
.container {
flex-direction:column;
width: 100%;
height: 100%;
}
index.hml
<div class ="container">
<text class="text">猜数字</text>
<text>请输入1到100的实数:</text>
<input type="text" name="number" id="number" value="{
{value}}"></input>
<button @click="guess">提交</button>
</div>
index.js
import prompt from '@system.prompt';
export default {
data(){
return {
ran: parseInt(Math.random()*100),
value:""
}
},
guess(){
var number = this.value;
if (number < 0 || number > 100) {
prompt.showToast({
message: '请输入1到100的实数',
duration: 2000,
});
} else if (this.ran == number) {
prompt.showToast({
message: '恭喜你猜对了,你猜的数字是' + this.ran,
duration: 2000,
});
} else if (this.ran > number) {
prompt.showToast({
message: '很遗憾,你猜小了',
duration: 2000,
});
} else if (this.ran < number) {
prompt.showToast({
message: '很遗憾,你猜大了',
duration: 2000,
});
}
}
}
效果图:
转载:https://blog.csdn.net/qq_42783654/article/details/108753757
查看评论