我们有一个 Vue 应用程序,并希望允许第三方创建插件。我们希望插件以 Vue 单文件组件的形式构建。
在运行时,最终用户会选择一个插件添加到应用程序中。该应用程序将获取纯文本 .vue 文件,即时编译它,并将其显示在应用程序中。
Vue 支持动态和异步组件,但这些需要提前编译到应用程序中。我们想做同样的事情,除了动态加载代码。
我怎样才能使这项工作?
这是我到目前为止所得到的:
<template>
<div>
The component goes here:
<component :is="pluginComponent"></component>
</div>
</template>
<script>
import { parseComponent } from "vue-template-compiler";
export default {
data() {
return {
pluginComponent: null
};
},
mounted() {
// fetch code from some external source here
let code = "<template><div>hello</div></template>";
let comp = parseComponent(code);
this.pluginComponent = comp;
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
(我修改了构建,所以 vue-template-compiler 存在。)
上面的代码生成此错误:
[Vue warn]: invalid template option:[object Object]
found in
---> <Anonymous> …Run Code Online (Sandbox Code Playgroud) 为了使用动态定义的单页组件,我们使用component标签,因此:
<component v-bind:is="componentName" :prop="someProperty"/>
...
import DynamicComponent from '@/components/DynamicComponent.vue';
...
components: {
DynamicComponent
},
props: {
componentName: String,
someProperty: null,
}
Run Code Online (Sandbox Code Playgroud)
问题是,这根本不是很动态,因为我们可能想在这里使用的每个组件不仅需要静态导入,而且还需要在components.
我们尝试这样做,至少是为了避免导入所有内容的需要:
created() {
import(`@/components/${this.componentName}.vue`);
},
Run Code Online (Sandbox Code Playgroud)
但当然这失败了,因为似乎DynamicComponent必须在到达之前定义created()。
我们如何使用真正动态的组件,即在运行时导入和注册,仅给出其名称?
我正在仪表板父项中渲染动态组件。如果有一个组件,它将呈现。如果没有,那...就没有了。问题是我目前唯一的动态组件被渲染了两次。
我尝试了有条件的渲染等,但是没有任何效果。
我将在此处发布一些代码,但是您正在使用Sandbox,所以也许更好。
没有控制台错误,只有几个警告。有任何想法吗?
我使用vue3 beta 18,发现当我删除由v-for中的动态组件渲染的组件时,没有发出beforeDestroy。
两者都没有停用,销毁。
当我从集合“windows”中删除它时,该组件“消失了”。
<template>
component(v-for="ww in windows" :key="ww.$id" :is="ww.component" v-bind="ww.props")
</template>
Run Code Online (Sandbox Code Playgroud)