1

I was wondering if with Vue.js (v2), when rendering list, the :key attribute applied on items must have a maximum size ? And if so, what is this limit ?

As a use case, I was considering using :key=JSON.stringify(item) as I'm designing a component that can handle list whose items can have various types. Is this a bad practice ?

Thanks for your input on this !

Watchoutman
  • 37
  • 1
  • 10

1 Answers1

1

Technically, the maximum length would most likely be limited by the maximum length of a string in the given browser. Realistically though, I would strongly advise against it.

Keys are used by Vue to track item identity. What this means is that when you have an initial list with keys shown on the left that's then updated to the one on the right, Vue can simply reorder most of the items instead of rerendering the full list from scratch.

┌───┐    ┌───┐  
│ 1 │    │ 5 │
├───┤    ├───┤
│ 2 │    │ 4 │
├───┤ -> ├───┤
│ 3 │    │ 3 │
├───┤    ├───┤
│ 4 │    │ 2 │
└───┘    └───┘

In the above example, nodes 2, 3 and 4 can be reordered, while node 5 will be rendered from scratch.
Reordering is considerably cheaper than rendering, thus making your application faster.

The overhead for doing this is essentially a sum of two things: comparing the keys on the left to the keys on the right, and then reordering the nodes you can reuse.
When you make your keys large, you'll likely nullify most or all of the benefit of this operation as the key comparison time will grow. Additionally you'll use up a lot of memory which doesn't bode well for most mobile devices.

tony19
  • 125,647
  • 18
  • 229
  • 307
Etheryte
  • 24,589
  • 11
  • 71
  • 116