<!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><!-- 鍵盤區(qū)域 --><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部分----------------------------------------------------------------------//創(chuàng)建倉庫storeconst store = new Vuex.Store({ state:{ result:"",//運算結果 enter:""http://輸入的值 }, // 定義名為calculate的mutaion mutaions:{ calculate(state,value){ if(value === '='){? ? ? ? ? ? ? ?// 按鍵值為'='進行計算? ? ? ? ? ? ? ?state.result=eval(state.enter);? ? ? ? ? ? ? ?state.enter +=value; }else if(value==='clear'){ // 按鍵值clear,清空數(shù)據(jù) state.result =state.enter="" }else{ // 輸入結果enter進行拼接 state.enter +=value; } } }});// 定義組件Vue.component('keyboard',{ props:['value'], template:`<div @click="getKeyboardValue" :data-value="value">{{value}}</div>`, methods:{ // 點擊事件處理函數(shù) 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獲取倉庫的數(shù)據(jù)result return this.$store.state.result; }, enter(){ //通過this.$store獲取倉庫的數(shù)據(jù)enter return this.$store.state.enter; } } });
添加回答
舉報
0/150
提交
取消