利用Vue编写一个“计数器”

目录

一、利用Vue编写一个"计数器"的操作方法:

1、data中定义计数器的相关数据,如num、min、max。

2、methods中添加计数器的递增与递减方法,其中①递减sub方法:大于0递减;②递增add方法:小于10累加。

3、使用v-text将num设置给span标签。

4、使用v-on将add,sub分别绑定给+,-按钮。

二、html文件相关源代码

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>计数器</title>
  <link rel="stylesheet" href="./css/index.css">
</head>

<body>
  <div id="app">
    <div class="input-num">
      <!-- 4.1、使用v-on将sub绑定给-按钮 -->
      <button @click="sub">
        -
      </button>
      <!-- 3、使用v-text将num设置给span标签。 -->
      <span>{{ num }}</span>
      <!-- 4.2、使用v-on将add绑定给+按钮 -->
      <button @click="add">
        +
      </button>
    </div>
  </div>
</body>

</html>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: "#app",
    // 1、data中定义计数器的相关数据,如num、min、max。
    data: {
      num: 1,
      min: 0,
      max: 10
    },
    // 2、methods中添加计数器的递增与递减方法。
    methods: {
      // 2.1、递减sub方法:大于0递减
      sub() {
        if (this.num > this.min) {
          this.num--;
        } else {
          alert("别点啦,到底啦");
        }
      },
      // 2.2、递增add方法:小于10累加
      add() {
        if (this.num < this.max) {
          this.num++;
        } else {
          alert("别点啦,到头啦");
        }
      }
    }
  });
</script>

三、CSS文件相关源代码

css 复制代码
body{
  background-color: #f5f5f5;
}
#app {
  width: 480px;
  height: 80px;
  margin: 200px auto;
}
.input-num {
  margin-top:20px;
  height: 100%;
  display: flex;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 4px 4px 4px #adadad;
  border: 1px solid #c7c7c7;
  background-color: #c7c7c7;
}
.input-num button {
  width: 150px;
  height: 100%;
  font-size: 40px;
  color: #ad2a27;
  cursor: pointer;
  border: none;
  outline: none;
  background-color:rgba(0, 0, 0, 0);
}
.input-num span {
  height: 100%;
  font-size: 40px;
  flex: 1;
  text-align: center;
  line-height: 80px;
  font-family:auto;
  background-color: white;
}
img{
  float: right;
  margin-top: 50px;
}

四、代码执行效果展示如下

相关推荐
JosieBook28 分钟前
【SpringBoot】21-Spring Boot中Web页面抽取公共页面的完整实践
前端·spring boot·python
汇能感知1 小时前
光谱相机的探测器类型
经验分享·笔记·科技
吃饭睡觉打豆豆嘛1 小时前
深入剖析 Promise 实现:从原理到手写完整实现
前端·javascript
前端端1 小时前
claude code 原理分析
前端
GalaxyMeteor1 小时前
Elpis 开发框架搭建第二期 - Webpack5 实现工程化建设
前端
Spider_Man1 小时前
从 “不会迭代” 到 “面试加分”:JS 迭代器现场教学
前端·javascript·面试
我的写法有点潮1 小时前
最全Scss语法,赶紧收藏起来吧
前端·css
小高0071 小时前
🧙‍♂️ 老司机私藏清单:从“记事本”到“旗舰 IDE”,我只装了这 12 个插件
前端·javascript·vue.js
Mo_jon2 小时前
css 遮盖滚动条,鼠标移上显示
前端·css
EveryPossible2 小时前
终止异步操作
前端·javascript·vue.js