效果图:
body {
margin: 100px;
}
#app {
border: 1px solid #ccc;
width: 175px;
height: 285px;
padding: 10px;
border-radius: 4px;
}
#app .btn {
width: 40px;
height: 40px;
border: 1px solid #ccc;
border-radius: 2px;
background-color: white;
margin-bottom: 10px;
cursor: pointer;
color: #666;
font-weight: bold;
}
#app .btn:hover {
background-color: #333;
color: white;
}
#input-box {
width: 161px;
text-align: right;
height: 30px;
border: 1px solid #ccc;
border-radius: 2px;
margin-bottom: 10px;
background-color: white;
padding: 0 5px;
}
#app .btn-double {
width: 84px;
}
C
+/-
*
/
1
2
3
-
4
5
6
+
7
8
9
%
0
.
=
// 去掉提示
// Vue.config.productionTip=false
const resultBox = {
// 父子通信
props: ["getValue"],
// 计算属性
computed: {
value() {
return this.getValue
}
},
template: ``
}
const calcBox = {
template: `
`
}
const app = new Vue({
el: "#app",
data: {
resultvalue: 0
},
// 组件
components: {
// 计算器结果框
'result-box': resultBox,
// 计算器输入面板组件
'calc-box': calcBox
},
methods: {
// 输入数值 累加
input(param) {
// 拒绝开始0和反复0 防止0.被和谐
if (parseInt(this.resultvalue) === 0 && !/0[\.|\s]/.test(this.resultvalue)) {
this.resultvalue = param
} else {
this.resultvalue += param
}
},
// 加减乘除
sambol(param) {
// 有空格显得更加好看
this.resultvalue += ' ' + param + ' '
},
// 处理小数点
point() {
const strValue = this.toStr()
// 得到最后一位数值
const lastNumber = strValue.substring(strValue.lastIndexOf(' '))
// 判断是否已经存在小数点
// 存在
if (lastNumber.indexOf('.') !== -1) {
return
} else {
this.resultvalue += '.'
}
},
// 转换成字符串
toStr() {
return this.resultvalue.toString()
},
clear(){
this.resultvalue=0
},
// 正负号设置
sign(){
const strValue=this.toStr()
let lastNumber = strValue.substring(strValue.lastIndexOf(' '))
// 得到之前的数值+符号
let prevNumber=strValue.substr(0,strValue.lastIndexOf(' '))
// 判断当前是否有正负号
if(lastNumber.indexOf('-')===-1){
lastNumber=' -'+lastNumber.trim()
}
else{
lastNumber=' '+lastNumber.trim().substr(1)
}
this.resultvalue=prevNumber+lastNumber;
},
calculate(){
try{
this.resultvalue=eval(this.resultvalue)
}catch(e){
//TODO handle the exception
alert('no')
}
}
}
})