【问题标题】:Load vue component (truly) dynamically from local file从本地文件动态加载 vue 组件(真正)
【发布时间】:2020-12-21 00:31:58
【问题描述】:

是否可以在运行时动态加载 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."

  2. 使用 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 = '';
    },
  },
};

【问题讨论】:

    标签: vue.js plugins electron components


    【解决方案1】:

    您可能可以查看异步加载:

    https://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

    这些只是我会根据您的要求研究的一些内容。

    【讨论】:

    • 我已经阅读过这方面的内容,但那里的组件在编译时就已经知道并与 webpack 捆绑在一起。
    • 那么您可以采用 Web 组件方法。见medium.com/@kitson.mac/…
    【解决方案2】:

    我找到了解决办法:

    1. 将 vue 组件创建为一个单独的文件中的 SFC(此处为 src/Component.vue)。我没有尝试,但它可能也适用于内联组件。

    2. 如果项目是使用vue-cli创建的,使用vue-cli-service预编译组件,这已经是一个开发依赖项(这里使用vue-cli很好,因为已经包含了所需的加载器):

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

      组件在dist 目录中被编译成不同的bundle 类型。现在可以导入文件[filename].umd.min.js

    3. 在运行时动态导入组件:

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

      require 被包裹在 eval 中,以防止 webpack 尝试在其包中包含导入并将 require 转换为 webpack__require

    4. (可选)如果 SFC 组件包含 &lt;style&gt;...&lt;/style&gt; 标记,则生成的 css 将编译为单独的文件。通过在组件项目根目录中的vue.config.js 中添加以下几行,可以将 css 内联到 js 文件中:

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

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2020-01-21
      • 2018-05-22
      • 2020-09-14
      • 2020-01-24
      • 1970-01-01
      • 2021-01-25
      • 2018-07-08
      • 2019-06-30
      相关资源
      最近更新 更多