keep-alive是vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM;
keep-alive包裹动态组件的时候,会缓存不活动的组件实例,而不是销毁他们;
<div> <!-- 当点击button时 组件one-name会根据status状态来切换 --> <span @click="button1" style="padding: 0 25px;">button</span><span @click="button2">button1</span> </div> <!-- include: 字符串或正则表达式。只有匹配的组件会被缓存 <keep-alive :include='OnetName'> 将会缓存组件名为OnetName的组件--> <!-- exclude: 字符串或正则表达式。任何匹配的组件都不会被缓存 <keep-alive :exclude='OnetName'> 将不会缓存组件名为OnetName的组件--> <keep-alive > <one-name v-if="status"></one-name> </keep-alive>
被keep-alive缓存的组件(当点击button按钮时 如果是被keep-alive缓存的组件则 "vue实例化" -> "dom渲染完毕",如果没有被缓存,则会一直 "vue实例化" -> "dom渲染完毕"->"组件被销毁了")
<template> <el-row> <div @click="okClick">第一个组件{{num1}}</div> </el-row> </template> <script> export default { name: 'oneName', data() { return { num1: 0 } }, created () { console.log('vue实例化了') }, mounted () { console.log('dom渲染完毕') }, destroyed () { console.log('组件被销毁了') } } </script> <style scoped> </style>
来源:https://www.cnblogs.com/wjsy/p/12161880.html