keep-alive官网的解释和用法比较全面,其实仔细一想,大概就是最基本的保持本页面的数据状态逻辑展现不变,可以再次使用的意思吧
仅记录一下简单的使用过程:
index页面:
1 <template> 2 <keep-alive> 3 <div> 4 <h2>{{msg}}</h2> 5 <input placeholder="输入框"></input> 6 <button @click="stepPage">跳转page页</button> 7 </div> 8 </keep-alive> 9 </template> 10 11 <script> 12 export default { 13 name: "index", 14 data() { 15 return { 16 msg: "首页" 17 } 18 }, 19 methods:{ 20 stepPage(){ 21 this.$router.push('/page') 22 } 23 } 24 } 25 </script>
page页面:
1 <template> 2 <div> 3 <h2>{{msg}}</h2> 4 <button @click="stepIndex">跳转index页</button> 5 </div> 6 </template> 7 8 <script> 9 export default { 10 name: "page", 11 data(){ 12 return { 13 msg:"page页" 14 } 15 }, 16 methods:{ 17 stepIndex(){ 18 this.$router.push('/index') 19 } 20 } 21 } 22 </script>
router.js
{ path: '/', component: Home, name: '测试', children: [ { name: 'index', path: '/index', component: () => import('./pages/test/index'), meta: {keepAlive: true} }, { name: 'page', path: '/page', component: () => import('./pages/test/page'), meta: {keepAlive: true} } ] }
home.vue
1 <div class="layout-content"> 2 <div class="layout-content-main"> 3 <keep-alive> 4 <router-view v-if="$route.meta.keepAlive"></router-view> 5 </keep-alive> 6 <router-view v-if="!$route.meta.keepAlive"></router-view> 7 </div> 8 </div>
当组件在keep-alive内被切换时组件的activated、deactivated这两个生命周期钩子函数会被执行,进入index页面