- 页面第一次进入,钩子的触发顺序:created -> mounted -> activated
- 退出时触发deactivated
- 当再次进入时,只触发activated(不触发created等生命周期)
<div id="app"> <button vfor="tab in tabs" :key="tab" :class="{ active: currentTab === tab }" @click="currentTab = tab"> {{ tab }} </button> <keep-alive> <component :is="currentTabComponent" class="tab"></component> </keep-alive></div><script src="https://unpkg.com/vue@next"></script><script> const app = Vue.createApp({ data() { return { currentTab: 'Tab1', tabs: ['Tab1', 'Tab2'] } }, computed: { currentTabComponent() { return this.currentTab.toLowerCase() } } }) app.component('tab1', { template: `<div>Tab1 content</div>` }) app.component('tab2', { template: `<div> <input v-model="value" /> {{value}} </div>`, data() { return { value: 'hello' } }, created() { console.log('tab2 created') }, activated() { console.log('tab2 activated') } }) app.mount('#app')</script><style> .active { background: #e0e0e0; }</style>