从零使用vue脚手架开发一个简易的计算器

目录

1.环境

1.node的安装

2.创建vue项目

1.安装cli脚手架

2.创建项目

[3.vs code的安装](#3.vs code的安装)

4.找到项目目录

3.开发一个简易的计算器

1.开发一个按钮组件

2.使用button按钮

3.编写计算器界面UI

4.修改app.vue的内容如下

5.重新运行项目



1.环境

  1. 使用node版本
    1. v20.19.5
  2. npm 版本
    1. 10.8.2

1.node的安装

  1. 如果不知道node如何安装和配置,可以参考一下官网

    1. https://nodejs.cn/download/https://nodejs.cn/download/
    2. 这个是官网,安装简单直接下一步就可以了
    3. 然后设置一下镜像源就可以了
    4. 输入下面的指令就可以了

    npm config set registry http://registry.npm.taobao.org/
    7.

  2. 也可以使用nvm,可参考下面的一篇博客。简易使用上面的,比较简单

    1. https://blog.csdn.net/2301_76862031/article/details/140500534?spm=1011.2415.3001.5331https://blog.csdn.net/2301_76862031/article/details/140500534?spm=1011.2415.3001.5331

2.创建vue项目

1.安装cli脚手架

复制代码
  ```
  自己创建一个目录 然后输入cmd,点击回车就可以了
  ```
  1. npm install -g @vue/cli
  2. 出现下面的情况就算是安装成功了
  3. 验证版本
  4. vue --version

2.创建项目

复制代码
  ```
  vue create my-vue-app
  ```
  1. 点击Enter
  2. 等待安装即可
  3. 上面是安装成功了
  4. 输入 cd my-vue-app
  5. npm run serve
  6. 浏览器打开网址
  7. http://localhost:8080/
  8. vue项目创建成功了
  9. 关闭cmd窗口

3.vs code的安装

  1. https://code.visualstudio.com/https://code.visualstudio.com/
  2. 点击download 下载就可以了
  3. 然后一路next就可以了
  4. 这里就不做演示了

4.找到项目目录

  1. 拖拽到vscode上面
  2. 然后点击 trust
  3. 出现上面的界面就算是成功了
  4. 鼠标右键
  5. 点击Open in Integrated Terminal
  6. 输入 npm run serve
  7. 可以开始编写项目了
  8. 安装vue插件
    1. 然后我们的语法就有提示了

3.开发一个简易的计算器

1.开发一个按钮组件

  1. 找到package.json

    1. "globals": {

      "defineProps": "readonly",

      "defineEmits": "readonly",

      "defineExpose": "readonly",

      "withDefaults": "readonly"

      }

    2. 添加如上数据

    3. 重新启动 npm run serve

  2. 编写MyButton 代码

javascript 复制代码
<template>
  <div>
    <button 
      @click="changeColor" 
      class="dynamic-button" 
      :style="{ backgroundColor: buttonColor }"
    >
      {{ props.buttonText }}
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue'


const props = defineProps({
  buttonText: {
    type: String, 
    required: ''
  }
})

// 按钮初始的颜色
const buttonColor = ref('rgb(52, 152, 219)')

const changeColor = () => {
  // 生成RGB随机颜色
  const r = Math.floor(Math.random() * 256)
  const g = Math.floor(Math.random() * 256)
  const b = Math.floor(Math.random() * 256)
  
  buttonColor.value = `rgb(${r}, ${g}, ${b})`
}
</script>

<style scoped>
.dynamic-button {
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}
</style>
  1. 功能点击随机变化颜色
  2. 并且可以传入文本内容

2.使用button按钮

  1. 找到app.vue文件
  2. 修改里面的内容如下
javascript 复制代码
<template>
  <MyButton :buttonText="1"></MyButton>
</template>

<script setup>

</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


4. 找到main.js

  1. 挂载全局组件

  2. import MyButton from './components/MyButton.vue'

    // 挂载组件

    app.component('MyButton',MyButton)

复制代码
  ```javascript
  import { createApp } from 'vue'
  import App from './App.vue'

  import MyButton from './components/MyButton.vue'
  const app = createApp(App)

  // 挂载组件
  app.component('MyButton',MyButton)

  app.mount('#app')
  ```

  ![](https://i-blog.csdnimg.cn/direct/388f53fb542445e0a25d57d0fcc8d2eb.png)
  1. 打开网址可以看到我们的按钮

  2. http://localhost:8080/

  3. 每次点击按钮颜色都会发生不同的变化

3.编写计算器界面UI

复制代码
  ```javascript
  <template>
    <div class="calculator-container">
      <div class="calculator">
        <!-- 显示屏 -->
        <div class="display">
          <div class="previous-operand">{{ previousOperand }} {{ operation }}</div>
          <div class="current-operand">{{ currentOperand || '0' }}</div>
        </div>

        <!-- 按钮区域 -->
        <div class="buttons">
          <!-- 第一行 -->
            <MyButton :buttonText="'C'" @click="clear">C</MyButton>
            <MyButton :buttonText="'⌫'" @click="deleteLast"></MyButton>
            <MyButton :buttonText="'%'" @click="appendOperation('%')">%</MyButton>
            <MyButton :buttonText="'÷'" @click="appendOperation('÷')">÷</MyButton>


          <!-- 第二行 -->
           <MyButton  :buttonText="'7'" @click="appendNumber('7')">7</MyButton>
            <MyButton :buttonText="'8'"  @click="appendNumber('8')">8</MyButton>
            <MyButton :buttonText="'9'"  @click="appendNumber('9')">9</MyButton>
            <MyButton :buttonText="'x'"  @click="appendOperation('×')">×</MyButton>


          <!-- 第三行 -->
           <MyButton :buttonText="'4'"   @click="appendNumber('4')">4</MyButton>
            <MyButton :buttonText="'5'"  @click="appendNumber('5')">5</MyButton>
            <MyButton :buttonText="'6'"  @click="appendNumber('6')">6</MyButton>
            <MyButton :buttonText="'-'"  @click="appendOperation('-')">-</MyButton>


          <!-- 第四行 -->
           <MyButton :buttonText="'1'"  @click="appendNumber('1')" ></MyButton>
            <MyButton :buttonText="'2'"  @click="appendNumber('2')"></MyButton>
            <MyButton :buttonText="'3'"  @click="appendNumber('3')"></MyButton>
            <MyButton :buttonText="'+'"  @click="appendOperation('+')"></MyButton>


          <!-- 第五行 -->
           <MyButton :buttonText="'0'"  @click="appendNumber('0')">0</MyButton>
            <MyButton :buttonText="'.'"  @click="appendNumber('.')">.</MyButton>
            <MyButton :buttonText="'='"  @click="calculate">=</MyButton>
            

        </div>
      </div>
    </div>
  </template>

  <script setup>
  import { ref } from 'vue'

  // 计算器状态
  const currentOperand = ref('')
  const previousOperand = ref('')
  const operation = ref('')
  const shouldResetScreen = ref(false)

  // 添加数字
  const appendNumber = (number) => {
    if (shouldResetScreen.value) {
      currentOperand.value = ''
      shouldResetScreen.value = false
    }
    
    // 防止多个小数点
    if (number === '.' && currentOperand.value.includes('.')) return
    
    // 防止以0开头(除了0.)
    if (number === '0' && currentOperand.value === '0') return
    if (number !== '.' && currentOperand.value === '0') {
      currentOperand.value = number
      return
    }
    
    currentOperand.value += number
  }

  // 添加操作符
  const appendOperation = (op) => {
    if (currentOperand.value === '' && previousOperand.value === '') return
    
    if (currentOperand.value === '') {
      operation.value = op
      return
    }
    
    if (previousOperand.value !== '') {
      calculate()
    }
    
    operation.value = op
    previousOperand.value = currentOperand.value
    shouldResetScreen.value = true
  }

  // 计算结果
  const calculate = () => {
    if (previousOperand.value === '' || currentOperand.value === '' || operation.value === '') return
    
    const prev = parseFloat(previousOperand.value)
    const current = parseFloat(currentOperand.value)
    
    if (isNaN(prev) || isNaN(current)) return
    
    let computation
    switch (operation.value) {
      case '+':
        computation = prev + current
        break
      case '-':
        computation = prev - current
        break
      case '×':
        computation = prev * current
        break
      case '÷':
        computation = prev / current
        break
      case '%':
        computation = prev % current
        break
      default:
        return
    }
    
    currentOperand.value = computation.toString()
    operation.value = ''
    previousOperand.value = ''
    shouldResetScreen.value = true
  }

  // 清空
  const clear = () => {
    currentOperand.value = ''
    previousOperand.value = ''
    operation.value = ''
  }

  // 删除最后一位
  const deleteLast = () => {
    if (currentOperand.value === '') return
    currentOperand.value = currentOperand.value.slice(0, -1)
  }
  </script>

  <style scoped>
  .calculator-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
  }

  .calculator {
    background: #2d3748;
    border-radius: 20px;
    padding: 25px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
    width: 320px;
  }

  /* 显示屏样式 */
  .display {
    background: #1a202c;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    text-align: right;
    min-height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .previous-operand {
    color: #a0aec0;
    font-size: 14px;
    min-height: 20px;
  }

  .current-operand {
    color: white;
    font-size: 32px;
    font-weight: bold;
    word-wrap: break-word;
    word-break: break-all;
  }

  /* 按钮布局 */
  .buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
  }




  </style>
  ```

  ![](https://i-blog.csdnimg.cn/direct/7ab4249c68e8469e85aab892b13507ca.png)
  1. 这里主要使用ref函数,和一些函数的逻辑

    1. 清除数据,就是是数据置空 var_info = ''

    2. %加减乘除= 就是一些js内置的

    3. 使用switch根据传入 按钮 传入的值触发不同的功能

  2. 挂载组件

    javascript 复制代码
    import { createApp } from 'vue'
    import App from './App.vue'
    
    import MyButton from './components/MyButton.vue'
    import CaculatorUI from './components/CaculatorUI.vue'
    const app = createApp(App)
    
    // 挂载组件
    app.component('MyButton',MyButton)
    app.component('CaculatorUI',CaculatorUI)
    
    app.mount('#app')

4.修改app.vue的内容如下

复制代码
  ```javascript
  <template>
    <CaculatorUI></CaculatorUI>
  </template>

  <script setup>

  </script>

  <style>
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
  </style>
  ```

  ![](https://i-blog.csdnimg.cn/direct/3ba78b614c224efab4a41a9a3ae00747.png)

5.重新运行项目

  1. npm run serve
  2. 打开浏览器
  3. 可以看到我们的计算器界面

6.成品结果

相关推荐
小徐不会敲代码~18 小时前
Vue3 学习 5
前端·学习·vue
芳草萋萋鹦鹉洲哦1 天前
【pixijs】关于pixijs画圆
cocos2d·js
今天有个Bug1 天前
【计算机毕业设计】流浪动物救助平台 - SpringBoot+Vue
sql·mysql·spring·vue·毕业设计·课程设计
捧 花2 天前
前端如何调用后端接口(HTML + JS & Vue )
服务器·golang·vue·api·前后端交互
扶我起来还能学_2 天前
Vue3 proxy 数据响应式的简单实现
前端·javascript·vue
一颗青果2 天前
单例模式 | 死锁
linux·服务器·单例模式·1024程序员节
IT教程资源D2 天前
[N_101]基于springboot,vue企业网盘系统
mysql·vue·前后端分离·springboot网盘
星光一影2 天前
智慧停车与充电一体化管理平台:打造城市出行新生态
mysql·vue·能源·springboot·uniapp
dreams_dream2 天前
Element UI菜单折叠后的el-menu-item属性无法修改问题解决
前端·vue