先看效果
1.编辑器可以使用MonacoEditor。
2.新建组件,用来预览组件。
<template>
<div ref="main">
<component
:is="id"
v-if="reload"
@click="handleClick"
>
</component>
</div>
</template>
<script>
import Vue from "vue";
export default {
name: "vue",
props: ["option"],
data() {
return {
reload: false,
};
},
watch: {
content () {
this.initVue()
}
},
computed: {
content () {
return this.option.content;
},
id() {
return 'main-' + this.option.id;
},
},
mounted() {
this.initVue();
},
methods: {
async initVue() {
this.reload = false;
let template = this.getSource("template");
if (!template) return;
let script = this.getSource("script");
if (script) {
script = script.replace(/export default/, "return");
}
let styleCss = this.getSource("style");
let styleId = "style-" + this.id;
if (document.getElementById(styleId)) {
document.getElementById(styleId).remove();
}
let style = document.createElement("style");
style.id = styleId;
style.innerHTML = styleCss;
document.head.appendChild(style);
let obj = new Function(script)();
obj.template = template;
Vue.component(this.id, obj);
this.$nextTick(() => {
this.reload = true;
});
},
getSource(type) {
const reg = new RegExp(`<${type}[^>]*>`);
let content = this.content;
let matches = content.match(reg);
if (matches) {
let start = content.indexOf(matches[0]) + matches[0].length;
let end = content.lastIndexOf(`</${type}`);
return content.slice(start, end);
}
},
handleClick(item) {
this.updateClick(item || this.dataChart);
this.clickFormatter &&
this.clickFormatter(
{
data: item || this.dataChart,
},
this.getItemRefs()
);
},
},
};
</script>
3.在使用地方传入option, 把代码传入进来,就可以实现组件预览功能。这是我传入option的内容
4.如果预览报错无法展示,可以在vue.config.js添加如下配置
5.代码借鉴avuedata大屏一些代码如有侵犯联系作者删除文章