wk-keep-alive-item.vue 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <template>
  2. <view v-if="drawFlag" v-show="showFlag" class="wk-keep-alive-item">
  3. <slot />
  4. </view>
  5. </template>
  6. <script>
  7. /**
  8. * keep alive 子项(注:该组件不能单独使用,需配合 wk-keep-alive 组件使用)
  9. * @author yxk
  10. */
  11. export default {
  12. name: 'WkKeepAliveItem',
  13. data() {
  14. return {
  15. drawFlag: false,
  16. showFlag: false,
  17. isCreatedOk: false,
  18. flag: false
  19. }
  20. },
  21. watch: {
  22. flag: {
  23. handler(val) {
  24. this.$nextTick(function() {
  25. if (val) {
  26. this.drawFlag = true
  27. this.showFlag = true
  28. this.runActivated()
  29. } else {
  30. if (this.drawFlag === true) {
  31. this.runDeActivated()
  32. }
  33. this.showFlag = false
  34. }
  35. })
  36. }
  37. }
  38. },
  39. methods: {
  40. /**
  41. * 执行子组件 wkActivated 钩子(模仿 Vue activated 生命周期钩子)
  42. */
  43. runActivated() {
  44. let vnodes = null
  45. // #ifdef MP-WEIXIN
  46. vnodes = this.$children
  47. // #endif
  48. // #ifndef MP-WEIXIN
  49. vnodes = this.$slots.default
  50. // #endif
  51. vnodes.forEach(node => {
  52. this.$nextTick(function() {
  53. if (!this.isCreatedOk) {
  54. this.isCreatedOk = true
  55. }
  56. const that = node.componentInstance || node
  57. console.log('vnodes', that)
  58. const options = that.$options
  59. // 第一次 created 时不触发 wkActivated 钩子
  60. // if (
  61. // options.wkActivated &&
  62. // this.isCreatedOk &&
  63. // typeof options.wkActivated === 'function'
  64. // ) {
  65. // console.log('run wkActivated')
  66. // options.wkActivated.call(that)
  67. // }
  68. if (
  69. options.wkActivated &&
  70. typeof options.wkActivated === 'function'
  71. ) {
  72. console.log('run wkActivated')
  73. options.wkActivated.call(that)
  74. }
  75. })
  76. })
  77. },
  78. /**
  79. * 执行子组件 wkDeactivated 钩子(模仿 Vue deactivated 生命周期钩子)
  80. */
  81. runDeActivated() {
  82. let vnodes = null
  83. // #ifdef MP-WEIXIN
  84. vnodes = this.$children
  85. // #endif
  86. // #ifndef MP-WEIXIN
  87. vnodes = this.$slots.default
  88. // #endif
  89. vnodes.forEach(node => {
  90. this.$nextTick(function() {
  91. const that = node.componentInstance || node
  92. // const options = node.componentInstance.$options
  93. if (that.$options.wkDeactivated && typeof that.$options.wkDeactivated === 'function') {
  94. that.$options.wkDeactivated.call(that)
  95. }
  96. })
  97. })
  98. }
  99. }
  100. }
  101. </script>
  102. <style scoped lang="scss">
  103. </style>