最近在研究一個自動化項目, 讓使用者可以直接編輯網頁上得模塊 (用 Vue 寫的)
項目業務
1.首先 從數據庫 獲取 head 和 body 的innerHTML 文本
2.然後用 遞歸 循環 head ,body 的所有節點 其中包括 註釋節點, 轉換成 render 函數節點 (期間添加N多個自動化方法),這樣就可以在vue 中渲染頁面實現想要 自動化的功能
render 函數參數 使用方法簡介 :
render 中返回一個 h函數 h(元素名,{ 元素上綁定的,事件,attrs,style,class ....等 }, [子節點 h(...), h(...), h(...) , ...... ])
import Vue from 'vue'
let VNode = new Vue({
created () { // 生命週期 },
render ( h ) { // render 創建虛擬DOM 直到渲染
return h ('div', {...}, [...])
},
methods: { // 方法 },
data () {
return { // 數據 }
}
}).$mount()
export default VNode
小栗子:
// 遞歸所有DOM節點 生成 VNode 函數
childs (node, h) {
let childNode = []
let flage = false
node.childNodes.forEach(ele => {
if (ele.childNodes.length > 0) {
childNode.push(this.childs(ele, h))
} else {
if (ele.nodeType === 1) {
childNode.push(h(ele.tagName, this.setAttr(ele.attributes)))
} else {
if (ele.nodeType === 8) {
let notes = h('', {})
notes.text = ele.nodeValue
childNode.push(notes)
} else {
if (ele.nodeValue.replace(/\s/g, '') !== '') flage = true
childNode.push(ele.nodeValue)
}
}
}
})
return h(node.tagName, this.setAttr(node.attributes, flage), childNode)
},
// 還原 attributes 屬性
setAttr (attr, flage) {
let obj = {
style: {},
attrs: {},
on: {}
}
if (flage) obj.attrs['contenteditable'] = true
for (let key in attr) {
if (attr.hasOwnProperty(key)) {
if (attr[key].nodeName === 'href') {
obj.attrs[attr[key].nodeName] = path.resolve(__dirname, 'static/' + (attr[key].nodeValue.split('/').pop()))
} else if (attr[key].nodeName === 'src') {
obj.attrs[attr[key].nodeName] = path.resolve(__dirname, 'static/images/' + (attr[key].nodeValue.split('/').pop()))
} else {
obj.attrs[attr[key].nodeName] = attr[key].nodeValue
}
}
}
return obj
}
問題:
1. render 函數 怎麼添加字符串節點
h 函數 第一個參數 必須填 標籤名, 如果不填 就會渲染成 註釋的空節點 <!-- -->
所以最好 在子集數組中 push 字符串 自動生成字符串節點
我也試過 在對象中 添加 innerText 屬性, 虛擬節點時能看到結構, 但渲染真是DOM 後 添加innerText的元素 子級元素 就全沒了
h('div', {...}, ['我是字符串節點1', '我是字符串節點2'])
2. render 函數 怎麼添加 註釋節
let notes = h('', {}) // 首先創建一個空節點 render 會創建出一個
notes.text = '我是被註釋的內容'
此時 notes 虛擬節點 最後會被渲染成 : <-- 我是被註釋的內容 -->
VNode 虛擬節點屬性作用 參考
children 子節點,數組,也是VNode類型。
text 當前節點的文本,一般文本節點或註釋節點會有該屬性。
elm 當前虛擬節點對應的真實的DOM節點。
ns 節點的namespace。
context 編譯作用域。
functionalContext 函數化組件的作用域。
key 節點的key屬性,用於作爲節點的標識,有利於patch的優化。
componentOptions 創建組件實例時會用到的信息選項。
child 當前節點對應的組件實例。
parent 組件的佔位節點。
raw 原始html。
isStatic 靜態節點的標識。
isRootInsert 是否作爲根節點插入,被<transition>包裹的節點,該屬性的值爲false。
isComment 當前節點是否是註釋節點。
isCloned 當前節點是否爲克隆節點。
isOnce 當前節點是否有v-once指令。