让预览界面也能显示自定义的组件
前面已经实现了自定义.vue组件的添加,再编辑界面上也能正常使用。单当进行预览的时候却发现无法显示,这是因为预览的preview 页面是通过iframe 嵌套的另一个页面,与本编辑器不在同一个vue 应用中,所以这里需要重新注册组件。
生成preview 页面的代码主要在generator目录 下。
ml.png
让自定义组件可在preview 上运行需要一下3步:
1.在preview 的main.js 中全局注册自定义组件
// preview/main.js
import Vue from 'vue'
import { loadScriptQueue } from '@/utils/loadScript'
import Tinymce from '@/components/tinymce/index.vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import htitle from '../../components/render/aritical/htitle.vue' //引入自己的自定义组件
import mediaImg from '../../components/render/aritical/media_img.vue'
Vue.component('tinymce', Tinymce)
Vue.use(ElementUI)
Vue.component('htitle', htitle) //注册自己的自定义组件
Vue.component('mediaImg', mediaImg)
2.在generator/html.js 下的tag 对象添加自定义组件的html代码
tinymce: el => {
const { tag, vModel, placeholder } = attrBuilder(el)
const height = el.height ? `:height="${el.height}"` : ''
const branding = el.branding ? `:branding="${el.branding}"` : ''
return `<${tag} ${vModel} ${placeholder} ${height} ${branding}></${tag}>`
},
htitle: el => {
const { tag } = el.__config__
const conf = `:conf="formData.conf${el.__config__.formId}"`
return `<${tag} ${conf}></${tag}>`
},
mediaImg: el => {
const { tag } = el.__config__
const conf = `:conf="formData.conf${el.__config__.formId}"`
return `<${tag} ${conf}></${tag}>`
}
3.在generator/js.js 中添加组件所需的额外数据。我这里是为了偷懒把组件的所有的参数都放到了conf 中,原代码中是没有的,需要手动添加。
// 构建data
function buildData(scheme, dataList) {
// 在预览页面中需要把每个组件的conf 加入到data 中,方便每个自定义的组件获取自己的配置
dataList.push(`conf${scheme.__config__.formId}: ${JSON.stringify(scheme)},`)
}
这里由于我的目的是吧form-generator 改造成文章编辑器,表单的所有东西几乎都用不上,所以有很多的逻辑代码都被我删减了。目前还有很多遗留,只能等到吧所有的功能都完成的差不多时候再去统一处理。
再附上成功后的效果图:
48.png
5.png
66.png