Vue每日一題 - 創建一個計數器組件
今日題目:Vue基礎 - 數據綁定與事件處理
?? 練習要求:
創建一個簡單的計數器應用,實現以下功能:
1.
顯示當前計數值(初始值為0)
2.
提供"增加"按鈕,點擊時計數+1
3.
提供"減少"按鈕,點擊時計數-1
4.
提供"重置"按鈕,點擊時計數歸零
5.
當計數為負數時,數字顯示為紅色
6.
當計數為正數時,數字顯示為綠色
7.
當計數為0時,數字顯示為黑色
——————————————
題解:
點擊查看代碼
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue計數器練習</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<style>
.container {
text-align: center;
margin-top: 50px;
font-family: Arial, sans-serif;
}
.counter {
font-size: 48px;
font-weight: bold;
margin: 20px 0;
}
.positive { color: green; }
.negative { color: red; }
.zero { color: black; }
.btn {
font-size: 16px;
padding: 10px 20px;
margin: 0 10px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.btn-add { background-color: #4CAF50; color: white; }
.btn-subtract { background-color: #f44336; color: white; }
.btn-reset { background-color: #008CBA; color: white; }
.btn:hover { opacity: 0.8; }
</style>
</head>
<body>
<div id="app">
<div class="container">
<h1>Vue計數器</h1>
<div class="counter" :class="counterClass">{{ count }}</div>
<div>
<button class="btn btn-subtract" @click="decrease">減少 (-1)</button>
<button class="btn btn-reset" @click="reset">重置 (0)</button>
<button class="btn btn-add" @click="increase">增加 (+1)</button>
</div>
<p>當前狀態: {{ statusText }}</p>
</div>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
count: 0
};
},
computed: {
counterClass() {
if (this.count > 0) return 'positive';
if (this.count < 0) return 'negative';
return 'zero';
},
statusText() {
if (this.count > 0) return '正數狀態';
if (this.count < 0) return '負數狀態';
return '零值狀態';
}
},
methods: {
increase() {
this.count++;
},
decrease() {
this.count--;
},
reset() {
this.count = 0;
}
}
}).mount('#app');
</script>
</body>
</html>

浙公網安備 33010602011771號