1.制作思路
制作一個簡單的頁面計算器可以分為以下幾個步驟:
(1)創建 Vue 組件,包括顯示屏和按鈕組件。
(2)設置數據屬性,用于存儲計算器的當前狀態(如顯示屏上的數字)。
(3)編寫方法,實現計算器的基本功能(加減乘除等)。
(4)在模板中使用按鈕組件,并綁定點擊事件調用對應的方法。
2.具體代碼
<template>
? <div class="calculator">
? ? <div class="screen">{{ display }}</div>
? ? <div class="buttons">
? ? ? <button @click="appendToDisplay('7')">7</button>
? ? ? <button @click="appendToDisplay('8')">8</button>
? ? ? <!-- 其他數字按鈕 -->
? ? ? <button @click="calculate()">=</button>
? ? ? <button @click="clear()">C</button>
? ? </div>
? </div>
</template>
<script>
export default {
? data() {
? ? return {
? ? ? display: '0',
? ? ? currentInput: '',
? ? ? operator: null,
? ? ? result: null
? ? };
? },
? methods: {
? ? appendToDisplay(value) {
? ? ? if (this.display === '0' || this.result !== null) {
? ? ? ? this.display = value;
? ? ? ? this.result = null;
? ? ? } else {
? ? ? ? this.display += value;
? ? ? }
? ? ? this.currentInput += value;
? ? },
? ? clear() {
? ? ? this.display = '0';
? ? ? this.currentInput = '';
? ? ? this.operator = null;
? ? ? this.result = null;
? ? },
? ? calculate() {
? ? ? if (this.operator && this.currentInput !== '') {
? ? ? ? this.result = eval(this.display);
? ? ? ? this.display = this.result.toString();
? ? ? ? this.currentInput = this.result.toString();
? ? ? ? this.operator = null;
? ? ? }
? ? }
? }
};
</script>
<style>
.calculator {
? width: 200px;
? margin: 0 auto;
}
.screen {
? height: 40px;
? background-color: #f0f0f0;
? text-align: right;
? padding: 10px;
? font-size: 20px;
}
.buttons {
? display: grid;
? grid-template-columns: repeat(4, 1fr);
}
button {
? height: 50px;
? line-height: 50px;
? text-align: center;
? border: 1px solid #ccc;
}
</style>
注意:這是一個簡單的四則運算計算器示例,包含數字按鈕、清空按鈕和等號按鈕。你可以根據需要擴展功能,比如添加更多運算符、支持小數點、處理錯誤輸入等。