vue-项目试手(1) 计算器
界面搭建代码
这里使用的是传统的开发方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>迷你计算器</title>
<style>
body{
margin: 20px;
}
#app{
border: 1px solid #ccc;
border-radius: 4px;
width: 175px;
height: 285px;
padding: 10px;
}
#input-box{
width: 161px;
margin-bottom: 10px;
height: 30px;
border: 1px solid #ccc;
border-radius: 2px;
background-color: white;
color: #666;
padding: 0 5px;
text-align: right;
}
#app .btn{
width: 40px;
height: 35px;
border: 1px solid #ccc;
border-radius: 2px;
cursor: pointer;
background-color: white;
font-weight: bold;
color: #666;
margin-bottom: 10px;
}
#app .btn:hover{
background-color: #333;
color: white;
}
#app .btn-double{
width: 84px;
}
</style>
</head>
<body>
<div id="app">
<result-box></result-box>
<calc-box>
<button class="btn">C</button>
<button class="btn">+/-</button>
<button class="btn">x</button>
<button class="btn">÷</button>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">-</button>
<button class="btn">4</button>
<button class="btn">5</button>
<button class="btn">6</button>
<button class="btn">+</button>
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<button class="btn">%</button>
<button class="btn">0</button>
<button class="btn">.</button>
<button class="btn btn-double">=</button>
</calc-box>
</div>
<script src="../js/vue.js"></script>
<script>
//计算器结果框组件
const resultBox={
template:`
<input id="input-box" type="text">
`
}
//计算器输入组件面板组件
const calcBox={
template:`
<div id="calc-box">
<slot></slot>
</div>
`
}
const app =new Vue({
el:'#app',
data:{
resultValue:0
},
//组件
components:{
//计算器结果框组件
'result-box':resultBox,
//计算器输入组件面板组件
'calc-box': calcBox
}
})
</script>
</body>
</html>
效果:

逻辑处理
父子通信
使用v-bind 绑定好父子组件的关系

使用props实现父子组件通信

处理输入
编写方法 这个方法处理掉重复0
input(params){
//拒绝重复0
if(parseInt(this.resultValue)===0){
//转化成数字是0 就直接替换掉
this.resultValue=params
}
else {
this.resultValue+=params
}
}
在有数字的按钮加上这个方法

处理小数点
//处理小数点
point(){
const strValue=this.toStr()
//得到最后一位数值
const lastNumber=strValue.substring(strValue.lastIndexOf(' '))
//判断是否有小数点
if(lastNumber.indexOf('.')!==-1){
return
}
else{
this.resultValue+='.'
}
},

浙公网安备 33010602011771号