關于 Vue 中 h 函數的一些東西

最近在項目上需要一個信息彈窗 , 來顯示信息 。一開始只讓它彈出了文字 , 而且只有一條信息 。而給我的需求是多條文字和圖片,而后我使用了element ui中的 Notification 通知組件來顯示 。當然,基礎的 Notification 還不行,所以我使用了具有 HTML 片段的 Notification  , 以及搭配 Vue 中的h()函數一起來使用 。
下面是element ui 中給出的 Notification 組件(具有 HTML 片段的 Notification ) 。而要完成我的需求 , 只需在 Notification 的正文內容使用 h() 函數即可 。
1 ElNotification({2title: 'HTML String',3dangerouslyUseHTMLString: true,//是否將 message 屬性作為 HTML 片段處理4message: '<strong>This is <i>HTML</i> string</strong>',//正文內容5})當我使用 h() 函數之后:
1 ElNotification({ 2title: 'HTML String',//標題 3type: 'warning',//類型 4offset: 80,//相對屏幕頂部的偏移量 5customClass: 'temperature',//自定義類名 6dangerouslyUseHTMLString: true,//是否將 message 屬性作為 HTML 片段處理 7duration: 5000,//顯示時間 8message: h('div', [ 9h('img', { src: item[index].images[index], style: { width: '170px', height: '160px', float: 'left' } }),//插入的圖片10h('p', { class: 'userName', style: { color: 'orange', display: 'flex', margin: '0 0 0 15px' } }, '人員姓名:' + item[index].userName + ''),//插入的文字11],)代碼寫完了,接下來就講講 h() 函數以及它背后的 VNode (虛擬 DOM 節點 )
什么是 h() 函數?
Vue官方文檔是這樣解釋的:
Vue 提供了一個 h() 函數用于創建 vnodes 。
1 import { h } from 'vue'23 const vnode = h(4'div', // type5{ id: 'foo', class: 'bar' }, // props6[7/* children */8]9 )h() 是 hyperscript 的簡稱——意思是“能生成 HTML (超文本標記語言) 的 JavaScript” 。這個名字來源于許多虛擬 DOM 實現默認形成的約定 。一個更準確的名稱應該是 createVnode(),但當你需要多次使用渲染函數時,一個簡短的名字會更省力 。
h() 函數的使用方式非常的靈活:
1 // 除了類型必填以外,其他的參數都是可選的 2 h('div') 3 h('div', { id: 'foo' }) 4 5 // attribute 和 property 都能在 prop 中書寫 6 // Vue 會自動將它們分配到正確的位置 7 h('div', { class: 'bar', innerHTML: 'hello' }) 8 9 // props modifiers such as .prop and .attr can be added10 // with '.' and `^' prefixes respectively11 h('div', { '.name': 'some-name', '^width': '100' })1213 // 類與樣式可以像在模板中一樣14 // 用數組或對象的形式書寫15 h('div', { class: [foo, { bar }], style: { color: 'red' } })1617 // 事件監聽器應以 onXxx 的形式書寫18 h('div', { onClick: () => {} })1920 // children 可以是一個字符串21 h('div', { id: 'foo' }, 'hello')2223 // 沒有 props 時可以省略不寫24 h('div', 'hello')25 h('div', [h('span', 'hello')])2627 // children 數組可以同時包含 vnodes 與字符串28 h('div', ['hello', h('span', 'hello')])得到的 vnode 為如下形式:
1 const vnode = h('div', { id: 'foo' }, [])23 vnode.type // 'div'4 vnode.props // { id: 'foo' }5 vnode.children // []6 vnode.key // null(完整的 VNode 接口包含其他內部屬性,但是強烈建議避免使用這些沒有在這里列舉出的屬性 。這樣能夠避免因內部屬性變更而導致的不兼容性問題 。)
所以總結下來,使用方法(很簡單):

    推薦閱讀