vue 设计一个具备组件交互的代码类?

比如我有 Parent Child 两个组件
Parent 组件 onMounted
去触发 Childrequest renderData 方法
我想得到的结果如下

[
    {
        name:'Parent',
        model:'parent',
        onMounted:function(){
            this.$refs.child.request()
            this.$refs.child.renderData()
        }
    },
    {
        name:'Child',
        model:'child'
    }
]

我自己设计的代码长这样

// 组件对应的基础配置
const INSTANCE_CONFIG_MAP = new Map([
  ['Parent', {
    model: 'parent'
  }],
  ['Child', {
    model: 'child'
  }]
])
class Chain {
  constructor() {
    this.chainMap = new Map()
    this.lastEvent = null // 最近触发的一次事件
    this.lastName = null// 最近触发的事件的组件名
  }
  get result() {
    return Array.from(this.chainMap).map(([key, value]) => ({ ...value, name: key }))
  }
  get lastItemInMap() {
    return Array.from(this.chainMap)[this.chainMap.size - 1]
  }
  // 创建组件
  create(name) {
    if (this.chainMap.get(name)) return console.log(`chainMap'name must be unique`)
    const config = INSTANCE_CONFIG_MAP.get(name)
    this.chainMap.set(name, config)
    return this
  }
  // 响应事件
  on(event) {
    const [name, value] = this.lastItemInMap
    this.lastName = name
    this.lastEvent = event
    value[event] = null
    INSTANCE_CONFIG_MAP.set(name, value)
    return this
  }
  // 触发方法
  dispatch(method) {
    const [name] = this.lastItemInMap
    const prevEventIns = INSTANCE_CONFIG_MAP.get(this.lastName)
    // 这里不知道怎么兼容触发多个方法, 求大佬指点
    prevEventIns[this.lastEvent] = function(...args) {
      const vueIns = this.$refs[name]
      vueIns[method].apply(vueIns,argsÏ)
    }
    return this
  }
}

const ins = new Chain().create('Parent').on('onMounted').create('Child').dispatch('request').dispatch('renderData')
console.log('🚀 ~ ins', ins.result[0].onMounted)

这样就会导致 renderData 覆盖了 request 方法,跪求大佬指教!

阅读 1.1k
1 个回答
// ...
value[event] = []
// ...
prevEventIns[this.lastEvent].push(function(...args) {
    const vueIns = this.$refs[name]
    vueIns[method].apply(vueIns,argsÏ)
})
// ...

这个意思?

说实话没太看懂要做什么,如果是希望在父组件onMounted钩子中,执行子组件的request方法和renderData。那么子组件不能在自己的生命周期执行这两个动作,难道是因为父组件在onMounted时会做一个什么操作给子组件提供必要的数据?那子组件直接watch也行吧,或者干脆让父组件代为处理,将结果下发给子组件。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题