更好的解决方案是使用外部库从对象的值生成哈希码并将其用作 id。即对象哈希
一个使用的例子object-hash
const hash = objectHash; // this should be the import i.e. require('object-hash');
new Vue({
el: '#app',
template: `
<div>
<p v-for="item in itemsWithHash" :key="item.key">
{{item.name}} {{item.lastname}}<br>key: {{ item.key }}
</p>
</div>
`,
data: () => ({
items: [
{ name: 'john', lastname: 'doe' },
{ name: 'bob', lastname: 'smith' },
{ name: 'alice', lastname: 'james' }
]
}),
computed: {
itemsWithHash() {
return this.items.map(i => ({ ...i, key: hash(i) }));
}
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/object-hash@1.3.1/dist/object_hash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)
您可以使用index迭代的作为键,但请记住,如果您按索引更新项目,这不会触发视图上的更改。(Vue 使用 key 来检测变化,因此如果 key 没有更新,它不会重新渲染模板)
<div v-for="(item, i) in items" :key="i">
// some content.
</div>
Run Code Online (Sandbox Code Playgroud)
请注意下面的示例,其中直接按索引更改项目不会更新视图,而是将更改打印到控制台:
<div v-for="(item, i) in items" :key="i">
// some content.
</div>
Run Code Online (Sandbox Code Playgroud)
new Vue({
el: '#app',
template: `
<div>
<p v-for="(item, index) in items" :key="index">
{{item.name}} {{item.lastname}}<br>index: {{ index }}
<button @click="changeForMary(index)"> Replace with Mary Smith</button>
</p>
</div>
`,
data: () => ({
items: [
{ name: 'john', lastname: 'doe' },
{ name: 'bob', lastname: 'smith' },
{ name: 'alice', lastname: 'james' }
]
}),
methods: {
changeForMary(index){
this.items[index] = { name: 'mary', lastname: 'smith' };
console.log(`index ${index} changed to ${JSON.stringify(this.items[index], null, '\t')}`);
}
}
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8394 次 |
| 最近记录: |