index.js 1.66 KB
// 商品card
Component({
  externalClasses: ['custom-class'],
  relations: {
    '../sidebar-item/index': {
      type: 'child',
      linked: function (target) {
        // 每次有 custom-li 被插入时执行,target是该节点实例对象,触发在该节点 attached 生命周期之后
        console.log(target)
        this.setActive(this.data.activeKey);
      },
      linkChanged: function () {
        // 每次有 custom-li 被移动后执行,target是该节点实例对象,触发在该节点 moved 生命周期之后
      },
      unlinked: function () {
        // 每次有 custom-li 被移除时执行,target是该节点实例对象,触发在该节点 detached 生命周期之后
      }
    }

  },
  /**
   * 组件的属性列表
   */
  properties: {
    activeKey: {
      type: Number,
      default: 0,
      observer: function (key) {
        this.setActive(key)
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentActive: 0,
    children: []
  },

  methods: {

    // 设置选中
    setActive(key) {
      const child = this.getAllChild()
      const currentActive = this.data.currentActive
      const stack = [];
      this.setData({
        currentActive: key
      })
      if (currentActive !== key && child[currentActive]) {
        stack.push(child[currentActive].setActive(false));
      }
      if (child[key]) {
        stack.push(child[key].setActive(true));
      }
      return Promise.all(stack);
    },

    // 获取所有的子nodes
    getAllChild() {
      const nodes = this.getRelationNodes('../sidebar-item/index')
      this.setData({
        children: nodes
      })
      return nodes;
    },

  }

})