是否可以在运行时动态加载一个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 = '';
},
},
};
2条答案
按热度按时间2skhul331#
我找到了解决办法:
1.在一个单独的文件中创建一个SFC的vue组件(这里是
src/Component.vue
)。1.如果项目是使用vue-cli创建的,则使用vue-cli-service预编译组件,vue-cli-service已经是一个dev依赖项(在这里使用vue-cli很好,因为已经包含了所需的加载器):
组件在
dist
目录下编译成不同的包类型,现在可以导入文件[filename].umd.min.js
。1.在运行时动态导入组件:
require
被 Package 在eval
中,以防止webpack试图将导入包含在其包中,并将require
转换为webpack__require
。1.(可选)如果SFC组件包含
<style>...</style>
标记,则生成的css将编译到单独的文件中。通过将以下行添加到组件项目根目录中的vue.config.js
,可以将css内联到js文件中: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
这些只是我会为你的需求研究的一些东西。