如何从 root 在自定义元素中使用 vue router 和 vuex?

And*_*ter 6 javascript vue.js vue-router vuex vuejs3

我有一个带有嵌套自定义元素的项目。现在我需要 vuex 和 vue 路由器。如何从根自定义元素使用此包,然后在所有子自定义元素中使用?

目前我尝试只在每个组件中使用 vuex,如下所示:

<script>
import store from './store';

export default {
  setup() {
    const state = store.state;

    return { state };
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

这是带有嵌套自定义元素的演示项目

这是我的main.js文件代码:

import { defineCustomElement } from "./defineCustomElementWithStyles";
import App from "./App.ce.vue";

customElements.define("app-root", defineCustomElement(App));
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 21

Vue 插件需要应用程序实例,该实例没有为从defineCustomElement(). 作为解决方法,您可以在临时应用程序实例上安装插件,然后将生成的上下文复制到实际应用程序,如该实用程序(我们稍后将使用)中所示:

// defineCustomElementWithStyles.js
import { defineCustomElement as VueDefineCustomElement, h, createApp, getCurrentInstance } from 'vue'

export const defineCustomElement = (component, { plugins = [] } = {}) =>
  VueDefineCustomElement({
    render: () => h(component),
    setup() {
      const app = createApp()

      // install plugins
      plugins.forEach(app.use)

      const inst = getCurrentInstance()
      Object.assign(inst.appContext, app._context)
      Object.assign(inst.provides, app._context.provides)
    },
  })
Run Code Online (Sandbox Code Playgroud)

使用defineCustomElement()上面的而不是以下的vue

// main.js
import { defineCustomElement } from './defineCustomElementWithStyles'
import App from './App.ce.vue'
import store from './store'
import router from './router'

customElements.define(
  'app-root',
  defineCustomElement(App, {
    plugins: [store, router],
  })
)
Run Code Online (Sandbox Code Playgroud)

演示


Raz*_*i91 6

对 tony19 的解决方案进行一点修复:

export const defineCustomElementWrapped = (component, { plugins = [] } = {}) =>
  defineCustomElement({
    styles: component.styles, // <- this
    render: () => h(component),
    setup() {
      const app = createApp()

      // install plugins
      plugins.forEach(app.use)

      const inst = getCurrentInstance()
      Object.assign(inst.appContext, app._context)
      Object.assign(inst.provides, app._context.provides)
    },
  })
Run Code Online (Sandbox Code Playgroud)

进而

customElements.define(
  'app-root',
  defineCustomElementWrapped(App, {
    plugins: [store, router],
  })
)
Run Code Online (Sandbox Code Playgroud)

这还包括组件导出的样式

(如果你要改变它们的行为,我也不喜欢隐藏原始函数名称,所以我重命名了它)

可能还需要:

    styles: component.styles.map((style) => {
      return style
        .replace(":root", ":host") // <- rename :root values to :host
        .replace("body {", "#my-app {"); // <- in case of frameworks like bootstrap that styles directly body
    }),
Run Code Online (Sandbox Code Playgroud)