electron 从本地文件动态加载vue组件(真正)

70gysomp  于 2022-12-08  发布在  Electron
关注(0)|答案(2)|浏览(567)

是否可以在运行时动态加载一个vue组件(在电子应用程序中构建一个插件系统)?

  • 组件位于特定文件中
  • 其路径仅在运行时才知道
  • 组件可以被预编译(如果可能的话,不知道),也可以在运行时编译
  • 下面列出了一个简单的示例组件

我尝试了以下方法,但都失败了:
1.需要组件

<template>
  <component :is="currentComp"></component>
</template>

<script>
...
methods: {
  loadComponent(path) {
    const dynComp = eval('require(path)'); // use eval to prevent webpackresolving the require
    this.currentComp = dynComp;
  }
},
...
</script>

导入工作正常,但this.currentComp = dynComp;行失败,并显示错误消息:
Error in data(): "Error: An object could not be cloned."
1.使用here提供的代码,但将url替换为本地路径
失败并显示错误消息:

Failed to resolve async component: function MyComponent() {
  return externalComponent('/path/to/Component.vue');
}
Reason: TypeError: Chaining cycle detected for promise #<Promise>

使用的示例组件如下:

// Example component
module.exports = {
  template: `
  <div>
    <input v-model="value"/>
    <button @click="clear">Clear</button>
    <div>{{ value }}</div>
  </div>`,
  name: 'Example',
  data() {
    return {
      value: '',
    };
  },
  watch: {
    value(value) {
      console.log('change!');
    },
  },
  methods: {
    clear() {
      this.value = '';
    },
  },
};
2skhul33

2skhul331#

我找到了解决办法:
1.在一个单独的文件中创建一个SFC的vue组件(这里是src/Component.vue)。
1.如果项目是使用vue-cli创建的,则使用vue-cli-service预编译组件,vue-cli-service已经是一个dev依赖项(在这里使用vue-cli很好,因为已经包含了所需的加载器):

yarn vue-cli-service build --target lib src/Command.vue

组件在dist目录下编译成不同的包类型,现在可以导入文件[filename].umd.min.js
1.在运行时动态导入组件:

let MyComponent = eval(`require('/absolute/path/to/[filename].umd.min.js')`);
Vue.component('MyComponent', MyComponent);

require被 Package 在eval中,以防止webpack试图将导入包含在其包中,并将require转换为webpack__require
1.(可选)如果SFC组件包含<style>...</style>标记,则生成的css将编译到单独的文件中。通过将以下行添加到组件项目根目录中的vue.config.js,可以将css内联到js文件中:

module.exports = {
  ...
  css: {
    extract: false,
  },
};
lrl1mhuk

lrl1mhuk2#

您可能会了解异步加载:
https://v2.vuejs.org/v2/guide/components-dynamic-async.html#Async-Components
请参阅下面Webpack延迟加载示例:
https://vuedose.tips/dynamic-imports-in-vue-js-for-better-performance/#the-meat%3A
这些只是我会为你的需求研究的一些东西。

相关问题