index.js 1.9 KB
Newer Older
1
const instances = Object.create(null)
fxy060608's avatar
fxy060608 已提交
2

fxy060608's avatar
fxy060608 已提交
3 4
export const mocks = ['__route__', '__webviewId__', '__nodeid__']

fxy060608's avatar
fxy060608 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
export function initPage (pageOptions) {
  initComponent(pageOptions)
}

export function initComponent (componentOptions) {
  if (componentOptions.properties) { // ref
    componentOptions.properties.vueRef = {
      type: String,
      value: ''
    }
  }
  const oldAttached = componentOptions.lifetimes.attached
  componentOptions.lifetimes.attached = function () {
    oldAttached.call(this)
    // TODO 需要处理动态变化后的 refs
    initRefs.call(this)
  }
}

function initRefs () {
  this.selectAllComponents('.vue-ref', (components) => {
    components.forEach(component => {
      const ref = component.data.vueRef // 头条的组件 dataset 竟然是空的
      this.$vm.$refs[ref] = component.$vm || component
    })
  })
  this.selectAllComponents('.vue-ref-in-for', (forComponents) => {
    forComponents.forEach(component => {
      const ref = component.data.vueRef
      if (!this.$vm.$refs[ref]) {
        this.$vm.$refs[ref] = []
      }
      this.$vm.$refs[ref].push(component.$vm || component)
    })
  })
}

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
export function triggerLink (mpInstance) {
  const nodeId = mpInstance.__nodeid__ + ''
  const webviewId = mpInstance.__webviewId__ + ''

  instances[webviewId + '_' + nodeId] = mpInstance.$vm

  mpInstance.triggerEvent('__l', {
    nodeId,
    webviewId
  }, {
    bubbles: true,
    composed: true
  })
}
// TODO 目前有 bug,composed 不生效
export function handleLink (event) {
  const nodeId = event.detail.nodeId
  const webviewId = event.detail.webviewId

  const childVm = instances[webviewId + '_' + nodeId]

  if (childVm) {
    childVm.$parent = this.$vm
    childVm.$parent.$children.push(event.detail)

    childVm.$root = this.$vm.$root
    delete instances[webviewId + '_' + nodeId]
  }
}