vue3-calculator
Version:
A Vue 3 calculator component with scientific and standard modes
453 lines (357 loc) • 11.3 kB
Markdown
一个功能完整的 Vue 3 计算器组件,支持标准和科学计算模式。
- 🧮 标准计算器功能(加减乘除、百分比、平方根等)
- 🔬 科学计算器功能(三角函数、对数、指数、阶乘等)
- 💾 内存功能(MC、MR、M+、M-、MS)
- 📝 历史记录
- 🎨 现代化 UI 设计
- ⌨️ 键盘支持
- 📱 响应式设计
- 🔧 TypeScript 支持
- 🎯 高精度计算(基于 decimal.js)
```bash
npm install vue3-calculator
yarn add vue3-calculator
pnpm add vue3-calculator
```
```vue
<template>
<div>
<Calculator
:mode="calculatorMode"
@mode-change="handleModeChange"
@calculate="handleCalculate"
@error="handleError"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { Calculator } from "vue3-calculator";
import "vue3-calculator/dist/style.css";
const calculatorMode = ref<"standard" | "scientific">("standard");
function handleModeChange(mode: "standard" | "scientific") {
calculatorMode.value = mode;
console.log("计算器模式切换到:", mode);
}
function handleCalculate(result: string) {
console.log("计算结果:", result);
}
function handleError(error: string) {
console.error("计算错误:", error);
}
</script>
```
```typescript
import { createApp } from "vue";
import { install as CalculatorPlugin } from "vue3-calculator";
import "vue3-calculator/dist/style.css";
import App from "./App.vue";
const app = createApp(App);
app.use(CalculatorPlugin);
app.mount("#app");
```
如果你需要在其他组件中访问计算器的状态,可以直接使用 hook:
```vue
<template>
<div>
<p>当前显示: {{ displayText }}</p>
<p>计算表达式: {{ expressionText }}</p>
<p>内存值: {{ memoryValue }}</p>
<p>历史记录数量: {{ history.length }}</p>
<button @click="clearCalculator">清除</button>
<button @click="addToMemory">M+</button>
<button @click="recallMemory">MR</button>
</div>
</template>
<script setup lang="ts">
import { useCalculator } from "vue3-calculator";
const {
displayText,
expressionText,
memoryValue,
history,
clearAll,
memoryAdd,
memoryRecall
} = useCalculator();
function clearCalculator() {
clearAll();
}
function addToMemory() {
memoryAdd();
}
function recallMemory() {
memoryRecall();
}
</script>
```
```vue
<template>
<div class="calculator-container">
<!-- 完整功能的科学计算器 -->
<Calculator
mode="scientific"
:show-toolbar="true"
:show-memory="true"
:show-history="true"
@mode-change="onModeChange"
@calculate="onCalculate"
@error="onError"
@memory-change="onMemoryChange"
/>
<!-- 简化版标准计算器 -->
<Calculator
mode="standard"
:show-toolbar="false"
:show-memory="false"
:show-history="false"
class="simple-calculator"
/>
</div>
</template>
<script setup lang="ts">
import { Calculator } from "vue3-calculator";
import "vue3-calculator/dist/style.css";
function onModeChange(mode: 'standard' | 'scientific') {
console.log('模式切换:', mode);
}
function onCalculate(result: string) {
console.log('计算结果:', result);
// 可以在这里处理计算结果,比如发送到服务器
}
function onError(error: string) {
console.error('计算错误:', error);
// 可以在这里显示错误提示
}
function onMemoryChange(memoryValue: string) {
console.log('内存值变化:', memoryValue);
}
</script>
<style>
.calculator-container {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.simple-calculator {
max-width: 300px;
}
</style>
```
| 属性 | 类型 | 默认值 | 说明 |
| ------------- | ---------------------------- | ------------ | ---------------- |
| `mode` | `'standard' \| 'scientific'` | `'standard'` | 计算器模式 |
| `showToolbar` | `boolean` | `true` | 是否显示工具栏 |
| `showMemory` | `boolean` | `true` | 是否显示内存功能 |
| `showHistory` | `boolean` | `true` | 是否显示历史记录 |
| 事件名 | 参数 | 说明 |
| --------------- | ---------------------------------- | ------------------------ |
| `mode-change` | `mode: 'standard' \| 'scientific'` | 计算器模式改变时触发 |
| `calculate` | `result: string` | 计算完成时触发 |
| `error` | `error: string` | 计算出错时触发 |
| `memory-change` | `memoryValue: string` | 内存值变化时触发 |
| `history-add` | `historyItem: HistoryItem` | 添加历史记录时触发 |
| `clear` | - | 清除操作时触发 |
| `input` | `value: string` | 数字或操作符输入时触发 |
- `0-9`: 数字输入
- `+`, `-`, `*`, `/`: 基本运算符
- `Enter` 或 `=`: 等于
- `Escape`: 清除所有
- `Backspace`: 退格
- `.`: 小数点
- `%`: 百分号
组件使用 CSS 变量,你可以通过覆盖这些变量来自定义样式:
```css
.calculator {
/* 字体大小 */
--font-size-small: 11px;
--font-size-normal: 14px;
--font-size-large: 18px;
--font-size-display: 24px;
/* 颜色主题 */
--primary-color:
--secondary-color:
--background-color:
--text-color:
--border-color:
/* 按钮样式 */
--button-background:
--button-hover:
--button-active:
--button-operator:
--button-operator-hover:
/* 间距 */
--padding-small: 8px;
--padding-medium: 12px;
--padding-large: 16px;
--border-radius: 4px;
}
```
```css
.calculator.dark-theme {
--background-color:
--text-color:
--border-color:
--button-background:
--button-hover:
--button-active:
--primary-color:
--button-operator:
--button-operator-hover:
}
```
```css
.calculator .btn {
transition: all 0.2s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.calculator .btn:hover {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.calculator .btn-operator {
background: linear-gradient(135deg,
color: white;
border: none;
}
```
A: 本组件具有以下优势:
- 🎯 **高精度计算**:基于 Decimal.js,避免 JavaScript 浮点数精度问题
- 🔬 **功能完整**:支持标准和科学计算模式,包含完整的内存和历史功能
- 🛡️ **类型安全**:完整的 TypeScript 支持
- 🎨 **可定制**:丰富的 CSS 变量和样式定制选项
- ⚡ **性能优化**:基于 Vue 3 Composition API,响应式性能优秀
A: 组件内部使用 Decimal.js 处理所有数值计算,支持任意精度的大数运算,不会出现科学计数法显示问题。
A: 支持完整的键盘操作,包括数字键、运算符、回车计算、ESC清除等,详见键盘支持部分。
A: 组件提供了丰富的 CSS 变量,可以轻松自定义颜色、字体、间距等样式,也支持深色主题。
A: 打包后的组件大小约为 64KB (UMD) / 89KB (ES),包含了所有数学计算库,体积合理。
```typescript
interface CalculatorState {
displayText: Ref<string>; // 当前显示的数值
expressionText: Ref<string>; // 当前计算表达式
memoryValue: Ref<string>; // 内存中的值
history: Ref<HistoryItem[]>; // 计算历史记录
mode: Ref<'standard' | 'scientific'>; // 计算器模式
}
interface CalculatorActions {
// 基础操作
inputNumber: (num: string) => void;
inputOperator: (op: string) => void;
calculate: () => void;
clearAll: () => void;
clearEntry: () => void;
backspace: () => void;
// 内存操作
memoryClear: () => void;
memoryRecall: () => void;
memoryAdd: () => void;
memorySubtract: () => void;
memoryStore: () => void;
// 科学计算
calculateFunction: (func: string) => void;
// 模式切换
toggleMode: () => void;
}
```
```typescript
interface HistoryItem {
id: string;
expression: string;
result: string;
timestamp: number;
}
type CalculatorMode = 'standard' | 'scientific';
type OperatorType = '+' | '-' | '*' | '/' | '%' | '^' | '√' | 'sin' | 'cos' | 'tan' | 'ln' | 'log';
```
- Vue 3.3+
- decimal.js (用于高精度计算)
- big.js
- expr-eval
- mathjs
```bash
git clone <repository-url>
cd vue3-calculator
npm install
npm run dev
npm run build
npm run type-check
```
MIT License
欢迎提交 Issue 和 Pull Request!
- 基于 Decimal.js 实现,避免 JavaScript 浮点数精度问题
- 支持 16 位以上大数计算,不会出现科学计数法显示
- 内存操作支持高精度数值存储和计算
- 三角函数:sin, cos, tan, asin, acos, atan
- 对数函数:ln, log, log2, log10
- 指数函数:e^x, 10^x, x^y
- 其他函数:阶乘(n!)、平方根(√)、倒数(1/x)
- 常数:π(pi)、e(自然常数)
- **MC (Memory Clear)**: 清除内存
- **MR (Memory Recall)**: 读取内存值
- **M+ (Memory Add)**: 将当前值加到内存
- **M- (Memory Subtract)**: 从内存中减去当前值
- **MS (Memory Store)**: 将当前值存储到内存
- **M∨ (Memory List)**: 显示内存历史列表
- 自动保存计算历史
- 支持点击历史记录重新计算
- 清晰的表达式和结果显示
- 🎨 优化了计算器组件的样式设计,提升视觉效果
- ✨ 改进了全局CSS样式和按钮交互动画
- 🎯 完善了Windows计算器风格的主题色彩
- ⚡ 优化了用户界面的整体美观度和用户体验
- 🐛 修复了16位数字边界值的内存计算精度问题
- 🐛 修复了大数显示时可能出现科学计数法的问题
- ⚡ 优化了Decimal.js使用方式,提升计算性能
- 🔧 改进了数字格式化逻辑,确保大数完整显示
- 🐛 修复了从Pinia迁移到Composition API后的状态管理问题
- ⚡ 优化了组件的响应式性能
- 🎉 初始版本发布
- ✨ 支持标准和科学计算模式
- ✨ 完整的内存和历史记录功能
- ✨ TypeScript 支持
- ✨ 响应式设计