wk-keep-alive.vue 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <template>
  2. <view class="wk-keep-alive">
  3. <slot />
  4. </view>
  5. </template>
  6. <script>
  7. /**
  8. * 模拟 uni-app 支持 vue keep-alive 钩子
  9. * 该组件需配合 wk-keep-alive-item 组件使用
  10. * @property {Number} v-model/value 当前是第几个子组件为激活状态标志 (必须)
  11. * @author yxk
  12. *
  13. * @example
  14. * <wk-keep-alive v-model="activeIndex">
  15. * <wk-keep-alive-item>
  16. * <component1 />
  17. * </wk-keep-alive-item>
  18. * <wk-keep-alive-item>
  19. * <component2 />
  20. * </wk-keep-alive-item>
  21. * </wk-keep-alive>
  22. */
  23. export default {
  24. name: 'WkKeepAlive',
  25. props: {
  26. value: {
  27. type: Number,
  28. required: true
  29. }
  30. },
  31. data() {
  32. return {}
  33. },
  34. watch: {
  35. value() {
  36. this.changeActive()
  37. }
  38. },
  39. mounted() {
  40. this.changeActive()
  41. },
  42. methods: {
  43. /**
  44. * 修改激活状态
  45. */
  46. changeActive() {
  47. this.$nextTick(function() {
  48. // #ifdef MP-WEIXIN
  49. this.$children.forEach((node, index) => {
  50. if (index === this.value) {
  51. node.flag = true
  52. } else {
  53. node.flag = false
  54. }
  55. })
  56. // #endif
  57. // #ifndef MP-WEIXIN
  58. this.$slots.default.forEach((node, index) => {
  59. if (index === this.value) {
  60. node.componentInstance.flag = true
  61. } else {
  62. node.componentInstance.flag = false
  63. }
  64. })
  65. // #endif
  66. })
  67. }
  68. }
  69. }
  70. </script>
  71. <style scoped lang="scss">
  72. </style>