v-bind —The difference between using and not using a key

Asked 2 years ago, Updated 2 years ago, 51 views

I am studying Vue.js using http://gihyo.jp/dev/serial/01/vuejs/0002.
Among them,

<divid="example">
  <liv-for="item in items" v-bind:key="item.name">
    <p>{{item.name} is {{item.price}} yen;/p>
  </li>
</div>

When it says html and

<divid="example">
  <lib-for="item in items">
    <p>{{item.name} is {{item.price}} yen;/p>
  </li>
</div>

There are two types of html, js is the same code, and I don't know the difference between using v-bind:key and not using v-bind:key. What is the difference between having and not having a key?

html vue.js

2022-09-30 10:49

1 Answers

If you do not specify the key first, you are warned, and it is recommended that you specify it as much as possible.

Official Guide
List Rendering-key,

All items should be given unique key attributes so that Vue can track the identification of each node, and that existing elements can be re-used and sorted as discussed earlier.

In short, if you specify a key, the elements with the same key are considered the same before and after the change when the elements in the list change order, and the DOM element moves accordingly.

Otherwise, no DOM element moves and changes each element immediately.However, this should not be done because if the element being List Rendered is a (stateful) element with a "state" such as a form element, it will be an unintended behavior.The official guide also says so.

This standard mode is efficient.However, this is only appropriate when the drawn list does not depend on the state of the child components or the state of the temporary DOM. (Example: value of form input).

  • If you do not specify a key
    DEMO1(JSFiddle)
    Here's an example you shouldn't do above.Press the Shift button to rotate the list to the left.
    If you type in the text box and press the button, you will see that the text box has not moved.
  • If the
    key is specified DEMO2(JSFiddle)
    Now, when I shift, the text box will also be moved.During the shift, Vue moves the DOM element accordingly because it knows which element after the shift corresponds to which element before the shift based on the key.

In the example questionnaire, the DOM element shown in v-for is a stateless element, so there is no difference in behavior from the outside (although the internal behavior of how the changes are reflected changes).


2022-09-30 10:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.