• 页面第一次进入,钩子的触发顺序:created -> mounted -> activated
    • 退出时触发deactivated
    • 当再次进入时,只触发activated(不触发created等生命周期)
    1. <div id="app">
    2. <button vfor="tab in tabs" :key="tab" :class="{ active: currentTab === tab }"
    3. @click="currentTab = tab">
    4. {{ tab }}
    5. </button>
    6. <keep-alive>
    7. <component :is="currentTabComponent" class="tab"></component>
    8. </keep-alive>
    9. </div>
    10. <script src="https://unpkg.com/vue@next"></script>
    11. <script>
    12. const app = Vue.createApp({
    13. data() {
    14. return {
    15. currentTab: 'Tab1',
    16. tabs: ['Tab1', 'Tab2']
    17. }
    18. },
    19. computed: {
    20. currentTabComponent() { return this.currentTab.toLowerCase() }
    21. }
    22. })
    23. app.component('tab1', {
    24. template: `<div>Tab1 content</div>`
    25. })
    26. app.component('tab2', {
    27. template: `<div>
    28. <input v-model="value" /> {{value}}
    29. </div>`,
    30. data() { return { value: 'hello' } },
    31. created() { console.log('tab2 created') },
    32. activated() { console.log('tab2 activated') }
    33. })
    34. app.mount('#app')
    35. </script>
    36. <style>
    37. .active { background: #e0e0e0; }
    38. </style>