<template> <view> <view class="word-container"> <view class="word" v-for="(word, index) in words" :key="index">{{ word }}</view> </view> <input type="text" v-model="newWord" placeholder="请输入新单词"> <button @click="addWord" class="Add">添加</button> <input type="text" v-model="practiceWord" placeholder="请输入练习单词" > <button @click="removeWord" class="Remove">删除</button> <view class="timer">耗费时长:{{ timer }}</view> </view> </template> <script> export default { data() { return { words: ["H"], newWord: "", practiceWord: "", timer: 0, }; }, mounted() { setInterval(() => { this.timer++; }, 1000); }, methods: { addWord() { if (this.newWord) { this.words.push(this.newWord.trim()); this.newWord = ""; } }, removeWord() { for (let i = 0; i < this.words.length; i++) { if (this.words[i] === this.practiceWord) { this.words.splice(i, 1); break; } } }, }, }; </script> <style> .word-container { border: 1px solid red; display: flex; flex-wrap: wrap; justify-content: center; } .word { margin: 10px; padding: 10px; font-size: 24px; font-weight: bold; background-color: #f0f0f0; border-radius: 5px; text-align: center; } .Add {} .timer { font-size: 24px; margin-top: 20px; text-align: center; } </style>添加个功能实现当所有单词都删除后计时停止
时间: 2024-03-26 22:36:29 浏览: 52
可以在 `removeWord` 方法里添加判断,当所有单词都被删除后,停止计时器。可以使用 `if (this.words.length === 0) clearInterval(intervalId);` 的方式来停止计时器,其中 `intervalId` 是 `setInterval` 方法返回的计时器 id。修改后的代码如下:
```
<template>
<view>
<view class="word-container">
<view class="word" v-for="(word, index) in words" :key="index">
{{ word }}
</view>
</view>
<input type="text" v-model="newWord" placeholder="请输入新单词">
<button @click="addWord" class="Add">添加</button>
<input type="text" v-model="practiceWord" placeholder="请输入练习单词">
<button @click="removeWord" class="Remove">删除</button>
<view class="timer">耗费时长:{{ timer }}</view>
</view>
</template>
<script>
export default {
data() {
return {
words: ["H"],
newWord: "",
practiceWord: "",
timer: 0,
intervalId: null,
};
},
mounted() {
this.intervalId = setInterval(() => {
this.timer++;
}, 1000);
},
methods: {
addWord() {
if (this.newWord) {
this.words.push(this.newWord.trim());
this.newWord = "";
}
},
removeWord() {
for (let i = 0; i < this.words.length; i++) {
if (this.words[i] === this.practiceWord) {
this.words.splice(i, 1);
break;
}
}
if (this.words.length === 0) clearInterval(this.intervalId);
},
},
};
</script>
<style>
.word-container {
border: 1px solid red;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.word {
margin: 10px;
padding: 10px;
font-size: 24px;
font-weight: bold;
background-color: #f0f0f0;
border-radius: 5px;
text-align: center;
}
.Add {}
.timer {
font-size: 24px;
margin-top: 20px;
text-align: center;
}
</style>
```
阅读全文