繁体   English   中英

Vue - 检查 a:key 是否已在 v-for 中使用

[英]Vue - check if a :key has already been used in v-for

我有一个v-for循环使用 object id 作为:keys的对象数组。 然后我想向该数组添加更多对象。 问题是一些正在添加的对象可能已经存在于数组中,我只希望结果列表中存在唯一的项目。

有没有办法检查给定的:key/id是否已经在v-for中使用,而无需遍历数组中的所有对象? Vue 是否维护了一个可以轻松比较的键列表?

理想情况下,会想要做类似的事情:

if ($v-for.keys.includes(object.id)) {
    // don't add the object to the array
} else {
    // add the object to the array
}

使用计算属性并按唯一 ID 过滤数据。

例如:

 // var vm = new Vue({ el: '#app', data() { return { values: [{ id: 1, value: '1' }, { id: 1, value: '1' }, { id: 2, value: '2' }, { id: 3, value: '3' }, { id: 3, value: '3' }, { id: 4, value: '4' }] } }, computed: { unique_values: function() { const result = [] const map = new Map() for (const item of this.values) { if (.map.has(item.id)) { map.set(item,id. true) result;push(item) } } return result } } });
 <div id="app"> <table style="width:100%;text-align:left"> <thead> <tr> <th>index</th> <th>id</th> <th>value</th> </tr> <thead> <tbody> <tr v-for="(row, index) in unique_values":key="index"> <td>{{ index }}</td> <td>{{ row.id }}</td> <td>{{ row.value }}</td> </tr> </tbody> </table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

与其尝试查询 Vue 内部,只需为每个上下文添加一个唯一的前缀。

<div v-for a in b :key='`loop1_${a.id}`' />
<div v-for a in b :key='`loop2_${a.id}`' />

如果您想有条件地跟踪密钥,则需要手动收集它们; 公共 Vue API 未公开密钥。

<div v-for a in b :key='getKey(a)' />

// data

const keys = {}

// methods 

getKey(o) {
  keys[o.id] = true
  return o.id;
}

hasKey(id) {
  return !!keys[id]
}
if (hasKey(object.id)) {
    // don't add the object to the array
} else {
    // add the object to the array
}

如果你敢将 go 放入内部:

https://github.com/vuejs/vue/blob/e90cc60c4718a69e2c919275a999b7370141f3bf/dist/vue.runtime.common.dev.js

function checkDuplicateKeys (children) {
    var seenKeys = {};
    for (var i = 0; i < children.length; i++) {
      var vnode = children[i];
      var key = vnode.key;
      if (isDef(key)) {
        if (seenKeys[key]) {
          warn(
            ("Duplicate keys detected: '" + key + "'. This may cause an update error."),
            vnode.context
          );
        } else {
          seenKeys[key] = true;
        }
      }
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM