欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > 利用Vue编写一个“计数器”

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

2025/2/5 17:18:33 来源:https://blog.csdn.net/blbyu/article/details/145446550  浏览:    关键词:利用Vue编写一个“计数器”

目录

  • 一、利用Vue编写一个“计数器”的操作方法:
  • 二、html文件相关源代码
  • 三、CSS文件相关源代码
  • 四、代码执行效果展示如下

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

1、data中定义计数器的相关数据,如num、min、max。
2、methods中添加计数器的递增与递减方法,其中①递减sub方法:大于0递减;②递增add方法:小于10累加。
3、使用v-text将num设置给span标签。
4、使用v-on将add,sub分别绑定给+,-按钮。

二、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文件相关源代码

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;
}

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

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com