Skip to content

vue 组件上下文要如何绑定,全局注册的组件无法使用 #6

@DwCoder-a11y

Description

@DwCoder-a11y
<script setup>
import DialogContent from './components/DialogContent.vue'
import autodialog from 'autodialog.js'

function openDialog() {
  autodialog.show(DialogContent)
}
</script>

<template>
  <div class="w-full h-screen flex items-center justify-center gap-5">

    <div class="p-5 border border-gray-300 rounded shadow">
      <DialogContent></DialogContent>
    </div>

    <AButton type="primary" @click="openDialog">Button</AButton>
  </div>
</template>

<style scoped></style>
Image

我尝试自己重新定义注册器;没有成功

<script setup>
import DialogContent from './components/DialogContent.vue'
import autodialog, {Dialog} from 'autodialog.js'
import {createApp, h, getCurrentInstance} from "vue";

function getProvides(instance) {
  let provides = instance?.provides || {};
  if (instance?.parent) {
    provides = {...provides, ...getProvides(instance.parent)};
  }
  return provides;
}

const customVueAdapter = {
  render(Component, {panel, title, props = {}, onClose}) {

// 这里获取不到 app 实例
    const globeInstance = getCurrentInstance();
    const globeProvides = getProvides(globeInstance);
    const globeAppContext = globeInstance?.appContext ?? {};

    const app = createApp({
      setup() {
        const instance = getCurrentInstance();
        if (instance) {
          instance.provides = {...instance.provides, ...globeProvides};
          instance.appContext = globeAppContext;
        }

        return () => h(
            'div',
            {class: 'autodialog-vue-wrapper'},
            [
              title ? h('div', {class: 'autodialog-header'}, title) : null,
              h(Component, {...props, onClose}),
            ]
        )
      }
    });
    app.mount(panel)
    panel.__dialogInstance__ = app;
  },
  unmount(panel) {
    const inst = panel.__dialogInstance__;
    inst?.unmount?.();
    delete panel.__dialogInstance__
  }
}

// ✅ 注册自定义适配器(detect 可省略)
Dialog.registerAdapter({
  name: 'vue',
  adapter: customVueAdapter
})

function openDialog() {
  autodialog.show(DialogContent)
}


</script>

<template>
  <div class="w-full h-screen flex items-center justify-center">

    <div class="p-5 border border-gray-300 rounded shadow">
      <DialogContent></DialogContent>
    </div>

    <AButton type="primary" @click="openDialog">Button</AButton>
  </div>
</template>

<style scoped></style>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions