讓預(yù)覽界面也能顯示自定義的組件
前面已經(jīng)實(shí)現(xiàn)了自定義.vue組件的添加,再編輯界面上也能正常使用。單當(dāng)進(jìn)行預(yù)覽的時(shí)候卻發(fā)現(xiàn)無法顯示,這是因?yàn)轭A(yù)覽的preview 頁(yè)面是通過iframe 嵌套的另一個(gè)頁(yè)面,與本編輯器不在同一個(gè)vue 應(yīng)用中,所以這里需要重新注冊(cè)組件。
生成preview 頁(yè)面的代碼主要在generator目錄 下。

ml.png
讓自定義組件可在preview 上運(yùn)行需要一下3步:
1.在preview 的main.js 中全局注冊(cè)自定義組件
// 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) //注冊(cè)自己的自定義組件
Vue.component('mediaImg', mediaImg)
2.在generator/html.js 下的tag 對(duì)象添加自定義組件的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 中添加組件所需的額外數(shù)據(jù)。我這里是為了偷懶把組件的所有的參數(shù)都放到了conf 中,原代碼中是沒有的,需要手動(dòng)添加。
// 構(gòu)建data
function buildData(scheme, dataList) {
// 在預(yù)覽頁(yè)面中需要把每個(gè)組件的conf 加入到data 中,方便每個(gè)自定義的組件獲取自己的配置
dataList.push(`conf${scheme.__config__.formId}: ${JSON.stringify(scheme)},`)
}
這里由于我的目的是吧form-generator 改造成文章編輯器,表單的所有東西幾乎都用不上,所以有很多的邏輯代碼都被我刪減了。目前還有很多遺留,只能等到吧所有的功能都完成的差不多時(shí)候再去統(tǒng)一處理。
再附上成功后的效果圖:

48.png

5.png

66.png