<template>
  <view class="wk-keep-alive">
    <slot />
  </view>
</template>

<script>
	/**
	 * 模拟 uni-app 支持 vue keep-alive 钩子
	 * 该组件需配合 wk-keep-alive-item 组件使用
	 * @property {Number} v-model/value 当前是第几个子组件为激活状态标志 (必须)
	 * @author yxk
	 * 
	 * @example 
	 *  <wk-keep-alive v-model="activeIndex">
	 *    <wk-keep-alive-item>
	 *      <component1 />
	 *    </wk-keep-alive-item>
	 *    <wk-keep-alive-item>
	 *      <component2 />
	 *    </wk-keep-alive-item>
	 *  </wk-keep-alive>
	 */
  export default {
    name: 'WkKeepAlive',
    props: {
      value: {
        type: Number,
        required: true
      }
    },
    data() {
      return {}
    },
    watch: {
      value() {
        this.changeActive()
      }
    },
    mounted() {
      this.changeActive()
    },
    methods: {
      /**
       * 修改激活状态
       */
      changeActive() {
        this.$nextTick(function() {
          // #ifdef MP-WEIXIN
          this.$children.forEach((node, index) => {
            if (index === this.value) {
              node.flag = true
            } else {
              node.flag = false
            }
          })
          // #endif
          // #ifndef MP-WEIXIN
          this.$slots.default.forEach((node, index) => {
            if (index === this.value) {
              node.componentInstance.flag = true
            } else {
              node.componentInstance.flag = false
            }
          })
          // #endif
        })
      }
    }
  }
</script>

<style scoped lang="scss">
</style>
