← Back to Vue.js Course | Chapter 10: Best Practices | Lesson 5 of 6

keep-alive का उपयोग

keep-alive inactive components cache करता है ताकि destroy होने की बजाय वे अपनी state रखें।

In this page:

  1. keep-alive
Syntax
markup
<keep-alive>
  <component :is="currentComponent"></component>
</keep-alive>

keep-alive

dynamic components या router views को keep-alive में wrap करें और Vue इनके instances switch away होने पर memory में रखता है, data और scroll preserve करते हुए। include और exclude choose करते हैं कि क्या cache करना है और max cache limit करता है।

Cached components को activated और deactivated hooks मिलते हैं।

Note: memory use bound करने के लिए max attribute इस्तेमाल करें।

उदाहरण: keep-alive

markup
<!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="tab = tab === 'note-a' ? 'note-b' : 'note-a'">Switch</button>
  <keep-alive><component :is="tab"></component></keep-alive>
</div>
<script>
  const app = Vue.createApp({ data() { return { tab: "note-a" }; } });
  app.component("note-a", { data() { return { text: "draft" }; }, template: "<p>A: {{ text }} <button @click=\"text += '!'\">edit</button></p>" });
  app.component("note-b", { template: "<p>B</p>" });
  app.mount("#app");
  (async () => {
    document.querySelectorAll("button")[1].click(); await Vue.nextTick();     // edit A
    document.querySelectorAll("button")[0].click(); await Vue.nextTick();     // to B
    document.querySelectorAll("button")[0].click(); await Vue.nextTick();     // back to A
    console.log("state kept after switching:", document.querySelector("p").textContent);
  })();
</script>
</body>
</html>

<!-- Output:
Rendered: SwitchA: draft! edit
console: state kept after switching: A: draft! edit
-->
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. #}
आम गलतियां
  1. सब कुछ cache करना और memory leak करना
  2. यह उम्मीद करना कि created फिर से चलेगा
  3. activated hooks भूल जाना
चैप्टर सारांश
  • keep-alive instances cache करता है
  • Switching के बाद state बनी रहती है
  • include, exclude, max इसे control करते हैं
  • activated और deactivated hooks
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.