<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vuex——示例计算器</title> <script src="https://unpkg.com/vue@2.3.3/dist/vue.js" type="text/javascript"></script> <script src="https://unpkg.com/vue-router@2.5.3/dist/vue-router.js" type="text/javascript"></script> <script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js" type="text/javascript"></script> </head> <body> <style> .result{ background: #ccc; height:200px; width: 80%; text-align: right; font-size: 48px; position: relative; } .enter{ background: #ccc; height: 50px; width: 78%; text-align: right; font-size:32px; border-bottom: 1px solid white; padding-right: 2%; } .keys{ background: #eee; width: 80%; } .item{ width: 25%; height: 80px; display: inline-block; line-height: 80px; border-bottom: 1px solid white; text-align: center; cursor: pointer; } .item:hover{ background: #000; color: #ccc; } .item:first-child{ color: red; } .item:first-child:hover{ background: red; color: #ccc; } .item:last-child{ background: red; color: white; } .item:last-child:hover{ background: green; color: red; } </style> <div id="app"> <div class="result"> <!--绑定计算属性result--> <div style="position: absolute;bottom: 0;right: 2%;"> {{ result }} </div> </div> <div class="enter"> <!--绑定计算属性enter--> {{ enter === ""?0:enter }} </div> <div class="keys"> <div class="list"> <!--键盘区域--> <keyboard v-for="item in keys" :value="item"></keyboard> </div> </div> </div> <script> // 创建仓库store const store = new Vuex.Store({ state: { result: "", //运算结果 enter: "" //输入的值 }, mutations: { 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',{ //接受的参数value,代表键盘的值 props: ['value'], //模板 template: `<div class="item" @click="getKeyboardValue" :data-value="value"> {{value}} </div>`, methods: { // 点击事件处理函数 getKeyboardValue(event){ //获取当前的按键的值 let value = event.target.dataset.value; //通过commit提交mutation this.$store.commit('calculate', value); } } }); //创建Vue实例 const app = new Vue({ //挂载元素 el: "#app", //ES6语法,相当于"store":store 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获取仓库的数据result return this.$store.state.enter; } } }); </script> </body> </html>
代码抄自:https://mp.weixin.qq.com/s?__biz=MzA3MDg1NzQyNA==&mid=2649654627&idx=1&sn=85bb9d0dfe34ab464f984f5f3042be2e&chksm=872c42dcb05bcbca37d495b24dfccb4a0179101e557be4c0119ab5a218c406a736e595ba5131&scene=21#wechat_redirect
微信号:webjiaocheng/Web前端教程
谢谢