目录
将registerConfig的内容传出,让子组件都可以拿到
大致介绍
要实现在组件区拿到想要的组件,放到预览区进行展示。可以利用一个组件的映射关系,通过key来实现组件区和预览区的对应关系。在通过渲染函数进行渲染即可。
大体思路
就是我们可以创建一个类,这个类中包含了我们的所有组件以及组件中的映射关系,我们可以通过我们保存的映射关系来找到相应的组件(组件在组件区的展示状态、组件在预览区展示状态等等)。然后我们可以将这个类作为全局函数,让所有的子组件可以拿到这个组件列表以及组件之间的映射关系。子组件拿到之后,可以提取其中有用的状态信息来在组件区或者是预览区中进行渲染,同时可以添加css样式,这样就实现了组件区的组件展示。
创建组件区和预览区的对应关系
因为我们项目的组件库还没有搭建完成,所以现在还不能利用,所以,我们现在先引入element-plus作为我们的组件库,后续如果我们组件库搭建完成之后,我们再进行更换。
创建editor-config.jsx文件
// 列表区可以显示所有的物料
// key对应的组件映射关系
import {ElButton, ElInput} from 'element-plus'
function createEditorConfig() {
// 组件列表
const componentList = [];
// 组件映射关系
const componentMap = {};
return {
componentList,
componentMap,
register: (component) => {
componentList.push(component);
componentMap[component.key] = component;
}
}
}
export let registerConfig = createEditorConfig();
// console.log(registerConfig)
registerConfig.register({
label: '文本',
preview: () => <span>预览文本</span>,
render: () => <span>渲染文本</span>,
key: "text"
})
registerConfig.register({
label: '按钮',
preview: () => <ElButton>预览按钮</ElButton>,
render: () => <ElButton>渲染按钮</ElButton>,
key: "button"
})
registerConfig.register({
label: '输入框',
preview: () => <ElInput placeholder="预览输入框"></ElInput>,
render: () => <ElInput placeholder="渲染输入框"></ElInput>,
key: "input"
})
其中在register函数中,label即为组件的标题,perview()就是在组件区所展示的内容,render()就是在预览区所展示的组件。
将registerConfig的内容传出,让子组件都可以拿到
在App.vue中,添加内容
import {registerConfig as config} from "@/utils/editor-config";
setup(){
// 将组件的配置直接传出
provide('config',config);
}
在组件区将拿到的config进行渲染
在editor.jsx中,添加内容
const config = inject('config')
<div class="editor-left">
{/*根据注册列表 渲染对应的内容*/}
{config.componentList.map(component => (
<div
class='editor-left-item'
>
<span>{component.label}</span>
<div>{component.preview()}</div>
</div>
))}
给组件区渲染的内容添加样式
在editor.scss中,添加内容:
&-left {
left: 0;
&-item {
width: 250px;
margin: 20px auto;
display: flex;
justify-content: center;
align-items: center;
background: white;
padding: 20px;
box-sizing: border-box;
cursor: move;
user-select: none;
min-height: 100px;
position: relative;
> span {
position: absolute;
top: 0;
left: 0;
background: deepskyblue;
color: white;
padding: 4px;
}
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #ccc;
opacity: 0.2;
}
}
运行后的结果:
从上图中,我们可以看到我们组件区已经渲染完成了,在下一篇文章中,我们将要讲述如何将组件区的组件实现拖拽并展示到预览区。