修改下列代码错误<template> <form action="" @submit="addMsg"> <input v-model="newMsg" /> <button>addMsg</button> </form> <ul> <li v-for="msg in filteredMsgs" :key="msg.id"> <input type="checkbox" v-model="msg.checkFlag" /> {{msg.text}} <button @click="removeMsg(msg)">reduce</button> </li> </ul> <button @click="checkFlag = !checkFlag">{{checkFlag ? 'Show All' : 'Hide All'}}</button> </template> <script> let id = 0 ; export default { data() { return { newMsg : '', checkFlag : false, checkMsg : '', msgs : [ {id : id++ , text : 'msg1' , checkFlag : true}, {id : id++ , text : 'msg2' , checkFlag : false}, {id : id++ , text : 'msg3' , checkFlag : true} ], filteredMsgs : this.$computed(() => {return this.checkFlag ? this.checkFlag.filter((t) => !t.done) : this.checkFlag}) } }, methods: { addMsg() { let hasMsgFlag = false; for (let i = 0 ; i < this.msgs.length ; i++) { if (this.checkMsg == this.msgs[i]) { hasMsgFlag = true; break; } } if (hasMsgFlag) { alert("输入的值重复,请重新输入!"); return; } else { this.msgs.push({id : id++ , text : this.newMsg , checkFlag : this.checkFlag}); this.newMsg = '' } }, removeMsg(msg) { this.msgs = this.msgs.filter((t) => t != msg); } }, } </script> <style> </style>
时间: 2024-01-07 15:03:36 浏览: 74
以下是代码错误的修改:
```html
<template>
<div>
<form @submit.prevent="addMsg">
<input v-model="newMsg" />
<button type="submit">Add Msg</button>
</form>
<ul>
<li v-for="msg in filteredMsgs" :key="msg.id">
<input type="checkbox" v-model="msg.checkFlag" />
{{ msg.text }}
<button @click="removeMsg(msg)">Reduce</button>
</li>
</ul>
<button @click="checkFlag = !checkFlag">
{{ checkFlag ? 'Show All' : 'Hide All' }}
</button>
</div>
</template>
<script>
let id = 0;
export default {
data() {
return {
newMsg: '',
checkFlag: false,
checkMsg: '',
msgs: [
{ id: id++, text: 'msg1', checkFlag: true },
{ id: id++, text: 'msg2', checkFlag: false },
{ id: id++, text: 'msg3', checkFlag: true },
],
};
},
computed: {
filteredMsgs() {
return this.checkFlag
? this.msgs.filter((msg) => !msg.checkFlag)
: this.msgs;
},
},
methods: {
addMsg() {
if (this.newMsg.trim() === '') return;
if (this.msgs.some((msg) => msg.text === this.newMsg)) {
alert('输入的值重复,请重新输入!');
this.newMsg = '';
return;
}
this.msgs.push({
id: id++,
text: this.newMsg.trim(),
checkFlag: this.checkFlag,
});
this.newMsg = '';
},
removeMsg(msg) {
this.msgs = this.msgs.filter((t) => t !== msg);
},
},
};
</script>
```
主要的修改包括:
1. 将 `form` 标签的 `action` 属性移除,使用 `@submit.prevent` 阻止表单默认提交行为。
2. 在 `computed` 属性中添加 `filteredMsgs` 计算属性,过滤出未被选中的消息。
3. 在 `addMsg` 方法中,检查输入的值是否为空,且判断输入的值是否已存在于消息列表中。
4. 将 `removeMsg` 方法中的过滤条件改为 `t !== msg`,使用 `!==` 进行严格相等判断。
阅读全文