Vue中如何判断数组项是否存在于另一数组实现愿望单功能
问题定位
你代码中存在3处核心错误:
- 计算属性
checkExists无法接收参数,不能给v-for循环中的每个条目做单独的存在性判断 checkExists的filter回调没有返回find的执行结果,最终返回的是空数组,判断逻辑永远不生效- 模板中绑定的
removeToWishlist方法没有实现,点击移除按钮会抛出异常
修改方案
直接将存在性判断改为带参数的方法,补全移除逻辑即可:
<template> <div id="app"> <h2>已选总数:{{selectedEntries.length}}</h2> <div v-for="entry in entries" :key="entry.id"> <div class="content-wrap"> <h3>{{entry.title}}</h3> <button v-if="!checkExists(entry.id)" @click="addToWishlist(entry.id)">加入愿望单</button> <button v-else @click="removeToWishlist(entry.id)">移除愿望单</button> </div> </div> </div> </template> <script> export default { name: "App", data(){ return{ entries: [ { title: '条目一', id: 1 }, { title: '条目二', id: 2 }, { title: '条目三', id: 3 }, { title: '条目四', id: 4 }, { title: '条目五', id: 5 }, ], selectedEntries: JSON.parse(window.localStorage.getItem("wishlistItems")) || [] } }, methods:{ checkExists(entryId){ // 直接用some判断是否存在,性能更高 return this.selectedEntries.some(selected => selected.id === entryId) }, addToWishlist(entryId){ this.selectedEntries.push({ id: entryId }); window.localStorage.setItem("wishlistItems", JSON.stringify(this.selectedEntries)); }, removeToWishlist(entryId){ // 过滤掉要移除的条目 this.selectedEntries = this.selectedEntries.filter(selected => selected.id !== entryId) window.localStorage.setItem("wishlistItems", JSON.stringify(this.selectedEntries)); } } }; </script> <style scoped> .content-wrap{ display: flex; border: 1px solid; margin: 5px; padding: 5px; align-items: center; } .content-wrap h3{ text-transform: capitalize; width: 30%; } .content-wrap button{ border: none; padding: 10px 20px; height: 30px; background-color: #1d9a61; color: #fff; font-size: 16px; cursor: pointer; line-height: .7 } </style>
内容的提问来源于stack exchange,提问作者Joney Spark
相关产品推荐
相关产品推荐

