目录
- 一、利用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;
}