/** * Created by wanghonghao on 2022/09/29 */
import Vue from 'vue'
let tdAttrs = { style: { border: '1px solid #000', padding: '5px 30px', 'text-align': 'center', 'font-weight': 'normal' }}
let tableAttrs = { style: { 'border-collapse': 'collapse', margin: '0 auto' }}
function render(examList) {
let table = Vue.component('subject-table', {
render: function (h) {
return h('table', tableAttrs, [
h('thead', tableAttrs, [h('tr', {}, [h('th', tdAttrs, '日期'), h('th', tdAttrs, '时间'), h('th', tdAttrs, '科目')])]),
h(
'tbody',
{},
examList.map(item => h('tr', {}, [h('td', tdAttrs, item.date), h('td', tdAttrs, item.time), h('td', tdAttrs, item.subject)]))
)
])
}
})
let instance = Vue.extend(table)
// 插入子元素进行挂载 避免直接挂载到占位符所包含的<td>
let div = document.createElement('div')
div.setAttribute('id', 'table-div')
let td = document.querySelector('#subject-table')
td.innerText = ''
td.appendChild(div)
new instance().$mount('#table-div')
}
function append(examList) {
// 获取#subject 、#date、#time所在td
let el = document.querySelector('#subject') ?? document.querySelector('#date') ?? document.querySelector('#time')
if (el === null) {
return false
}
// 获取td节点数组 用于插入排序
let order = el.parentElement.childNodes
examList.forEach((item, index) => {
// 拼接html字符串
let str = ''
order.forEach((_item, _index) => {
str += '<td>' + item[_item.id] + '</td>'
})
// html字符串生成dom
const parser = new DOMParser()
// 向table标签中插入节点表格元素(tr、td)时必须使用<table></table>标签包裹,否则parseFromString方法会将tr和td标签自动删除
let node = parser.parseFromString('<table><tr>' + str + '</tr></table>', 'text/html')
// parseFromString转换的是document对象,无法append()直接进行插入,获取内部节点后再插入
el.parentElement.after(node.getElementsByTagName('tr')[0])
})
// 删除占位符所在行
el.parentElement.replaceWith('')
}
function renderTable(examList) {
let el = document.querySelector('#subject-table')
if (el === null) {
append(examList)
} else {
render(examList)
}
}
export default renderTable