<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="请输入练习单词"> <view class="timer">耗费时长:{{ timer }}</view> </view> </template> <script> export default { data() { return { words: ["Hello", "World", "Vue"], newWord: "", practiceWord: "", timer: 0, }; }, mounted() { setInterval(() => { this.timer++; }, 1000); }, methods: { addWord() { if (this.newWord) { this.words.push(this.newWord.trim()); this.newWord = ""; } }, }, }; </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>添加一个方法如果输入的单词和已存在单词一致则删除一致的单词
时间: 2023-07-19 15:45:03 浏览: 71
详解Angular 自定义结构指令
你可以在 methods 中添加一个名为 removeWord 的方法,实现遍历 words 数组,如果有与 practiceWord 相同的单词,则将其删除。
代码实现如下:
```
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;
}
}
}
},
```
你可以将 removeWord 方法绑定到一个按钮上,例如:
```
<button @click="removeWord" class="Remove">删除</button>
```
这样,当用户输入相同单词并点击删除按钮时,相同的单词将被删除。
阅读全文