<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算器</title>
</head>
<style>
.contain{
margin:100px 500px;
width: 500px;
height: 704px;
border: solid 1px #ccc;
}
.head{
position: relative;
width: 500px;
height: 200px;
background-color:#ccc;
}
.enter{
position: absolute;
font-size: 20px;
font-weight: 800;
width: 100%;
top:160px;
text-align: right;
}
.result{
font-size: 30px;
position: absolute;
text-align: right;
top:100px;
width: 100%;
}
.list{
width: 500px;
height: 600px;
}
.list div{
font-weight: 800;
font-size: 20px;
line-height: 124px;
text-align: center;
width: 123px;
height: 124px;
float: left;
border: solid 1px #ccc;
}
.list div:first-child{
color: red;
}
.list div:last-child{
background-color: red;
}
</style>
<body>
<div id="app">
<div>
<div>
<div>{{result}}</div>
<div>{{enter ===""?0:enter}}</div>
</div>
<div>
<div>
<!-- 键盘区域 -->
<keyboard v-for="item in keys" :value="item"></keyboard>
</div>
</div>
</div>
</div>
</body>
<script src="vue.js"></script>
<script src="vuex.js"></script>
<script src="calc_js.js"></script>
</html>
--------------------------------------------------js部分----------------------------------------------------------------------
//创建仓库store
const store = new Vuex.Store({
state:{
result:"",//运算结果
enter:""//输入的值
},
// 定义名为calculate的mutaion
mutaions:{
calculate(state,value){
if(value === '='){
// 按键值为'='进行计算
state.result=eval(state.enter);
state.enter +=value;
}else if(value==='clear'){
// 按键值clear,清空数据
state.result =state.enter=""
}else{
// 输入结果enter进行拼接
state.enter +=value;
}
}
}
});
// 定义组件
Vue.component('keyboard',{
props:['value'],
template:`<div @click="getKeyboardValue" :data-value="value">{{value}}</div>`,
methods:{
// 点击事件处理函数
getKeyboardValue(event){
// 获取当前按键值
let value = event.target.dataset.value;
// 通过commit提交mutaion
this.$store.commit('calculate',value)
}
}
});
const app = new Vue({
el:'#app',
store,
data:{
keys:[
'clear','+','-','*',
'7','8','9','/',
'4','5','6','0',
'1','2','3','='
]
},
computed:{
result(){
//通过this.$store获取仓库的数据result
return this.$store.state.result;
},
enter(){
//通过this.$store获取仓库的数据enter
return this.$store.state.enter;
}
}
});
mutaions 这个单词拼写错了