keep-alive.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { callHook } from 'core/instance/lifecycle'
  2. export default {
  3. name: 'keep-alive',
  4. _abstract: true,
  5. props: {
  6. child: Object
  7. },
  8. created () {
  9. this.cache = Object.create(null)
  10. },
  11. render () {
  12. const rawChild = this.child
  13. const realChild = getRealChild(this.child)
  14. const cid = realChild.componentOptions.Ctor.cid
  15. if (this.cache[cid]) {
  16. const child = realChild.child = this.cache[cid].child
  17. realChild.elm = this.$el = child.$el
  18. } else {
  19. this.cache[cid] = realChild
  20. }
  21. realChild.data.keepAlive = true
  22. return rawChild
  23. },
  24. destroyed () {
  25. for (const key in this.cache) {
  26. const vnode = this.cache[key]
  27. callHook(vnode.child, 'deactivated')
  28. vnode.child.$destroy()
  29. }
  30. }
  31. }
  32. // in case the child is also an abstract component, e.g. <transition-control>
  33. // we want to recrusively retrieve the real component to be rendered
  34. function getRealChild (vnode) {
  35. const compOptions = vnode && vnode.componentOptions
  36. if (compOptions && compOptions.Ctor.options._abstract) {
  37. return getRealChild(compOptions.propsData.child)
  38. } else {
  39. return vnode
  40. }
  41. }