Key विशेषता
key attribute हर list item को एक stable identity देता है ताकि Vue lists को सही तरीके से और efficiently update कर सके।
In this page:
Syntax
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
Key Attribute
जब एक list बदलती है, Vue elements को in place reuse करता है जब तक keys इसे न बताएँ कि कौन-सा item कौन-सा है। Stable, unique keys Vue को सही elements move, add, और remove करने देते हैं और component या input state को सही item से attached रखते हैं।
एक key बदलना Vue को element फिर से बनाने पर force करता है।
Note:
एक element की key बदलना इसे scratch से re-render करने पर force करने का एक तरीका है।
उदाहरण: Key attribute
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<button @click="shuffle">Reverse</button>
<ul>
<li v-for="t in todos" :key="t.id"><input :value="t.text"> {{ t.id }}</li>
</ul>
</div>
<script>
Vue.createApp({
data() { return { todos: [{ id: 1, text: "milk" }, { id: 2, text: "eggs" }, { id: 3, text: "tea" }] }; },
methods: { shuffle() { this.todos.reverse(); } },
}).mount("#app");
console.log("before:", [...document.querySelectorAll("li")].map((li) => li.textContent.trim()));
document.querySelector("button").click();
Vue.nextTick(() => console.log("after:", [...document.querySelectorAll("li")].map((li) => li.textContent.trim())));
</script>
</body>
</html>
<!-- Output:
Rendered: Reverse 3 2 1
console: before: 1,2,3
console: after: 3,2,1
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- reorderable lists पर key की तरह index इस्तेमाल करना
- non-unique keys इस्तेमाल करना
- keys की तरह objects इस्तेमाल करना
चैप्टर सारांश
- Keys list items identify करती हैं
- ये unique और stable होनी चाहिए
- गलत keys element state mix up कर देती हैं
- एक नई key element फिर से बनाती है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: