经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JSON » 查看文章
函数式组件劫持替代json封装element表格
来源:jb51  时间:2022/7/19 13:02:54  对本文有异议

背景

系统有个整改需求,要求系统内的所有表格支持本地动态列显隐,拖拽排序列位置,固定列功能,涉及的页面很多

上效果图:

思路

其实最开始想的肯定是json配置表单的形式,再由循环出来的列去控制对应的位置和属性 但是!很多页面啊!每个页面都要去转json配置意味着大量的工作量和极高的风险

能不能我就写个自己的组件来包一层,这样我就能实现最小改动的情况下只需要替换组件标签来实现这个功能

与实际的不同只是我将原来的el-table换成了hf-table,同时支持原本el-table的所有功能

想法与实践

el-table-column获取

我们不可能去自己实现一个el-table的组件,所以无非我们的组件就是在el-table的基础上套一层壳,给他加上一个设置按钮,同时设置的内容能够去影响整个表格的渲染。

那既然我们不自己实现el-table则意味着原先代码中的el-table-column我们要拿到,并且要传给el-table,这样我们才能去渲染出来原先的那个表格

在一个组件的实例中,我们能够通过vnode去获取到当前的一个虚拟dom,vnode去获取到当前的一个虚拟dom,vnode去获取到当前的一个虚拟dom,vnode有一个componentOptions组件配置项的属性,通过他的children就能获取到所有的el-table-column 虚拟dom数组

如何渲染表格

上一步我们已经拿到了所有的el-table-column虚拟dom,那怎么将虚拟dom去渲染成对应的表格组件呢?

这不render就该登场了吗!!

这个children就是我们拿到的el-table-column的数组,我们只需要将该虚拟dom的数组以组件属性的形式传传进来了,再创建一个el-table,将对应的children传给他!卧槽,这不就又和原本<el-table>xxx</el-table>的效果一毛一样吗,是的 ,我做的就是挂羊头卖狗肉。

也就是说,实际上我的hf-table只是劫持了el-table,他的作用只是拿到原本写的el-table-colunm的虚拟dom,去渲染成一个表格

操作表格

此时我们的任务已经完成大半了,就是我原本el-table的标签已经可以被替换了,那我们要做的就只剩下操作表格了。 实际我做的很简单,既然我已经拿到了所有的子节点,那我就在hf-table组件中去操作成我想要的数组,再丢给render函数去渲染就好了

组件代码

整个组件的代码,代码量除掉样式也就不到100行

  1. <template>
  2. <div class="hf-table">
  3. <el-popover
  4. placement="bottom-end"
  5. width="400"
  6. popper-class="table-cloumn-setting-popper"
  7. trigger="click"
  8. >
  9. <div class="setting-row-content">
  10. <draggable v-model="storageList" handle=".el-icon-s-operation" @end="updateTable">
  11. <div v-for="clo in storageList" :key="clo.label" class="setting-row">
  12. <i class="el-icon-s-operation" />
  13. <el-checkbox v-model="clo.show" class="label" @change="showOrHidden($event,clo)">{{ clo.label }}</el-checkbox>
  14. <el-button
  15. class="btn"
  16. size="mini"
  17. :type="clo.fixed === 'left' ? 'primary' : 'default'"
  18. @click="setFixed('left',clo)"
  19. >固定在左侧</el-button>
  20. <el-button
  21. class="btn"
  22. size="mini"
  23. :type="clo.fixed === 'right' ? 'primary' : 'default'"
  24. @click="setFixed('right',clo)"
  25. >固定在右侧</el-button>
  26. </div>
  27. </draggable>
  28. </div>
  29. <i slot="reference" class="el-icon-setting" />
  30. </el-popover>
  31. <new-table v-if="showTable" :config="config" />
  32. </div>
  33. </template>
  34. <script>
  35. import draggable from 'vuedraggable'
  36. import newTable from './table.js'
  37. const components = { newTable, draggable }
  38. export default {
  39. components,
  40. props: {
  41. storageName: {
  42. type: String,
  43. default: 'hfTable'
  44. }
  45. },
  46. data() {
  47. return {
  48. showTable: false,
  49. storageList: [],
  50. name: '',
  51. config: {
  52. children: [],
  53. attrs: {},
  54. listeners: {}
  55. }
  56. }
  57. },
  58. watch: {
  59. '$attrs': {
  60. handler(newV) {
  61. this.$set(this.config, 'attrs', newV)
  62. },
  63. deep: true,
  64. immediate: true
  65. }
  66. },
  67. mounted() {
  68. this.initStorage()
  69. this.updateTable()
  70. },
  71. methods: {
  72. showOrHidden(val, clo) {
  73. if (!val && this.storageList.filter(i => i.show).length === 0) {
  74. this.$message.warning('列表最少显示一列')
  75. this.$nextTick(() => {
  76. clo.show = true
  77. })
  78. return
  79. }
  80. this.updateTable()
  81. },
  82. setFixed(value, clo) {
  83. if (clo.fixed === value) {
  84. clo.fixed = false
  85. } else {
  86. clo.fixed = value
  87. }
  88. this.updateTable()
  89. },
  90. // 初始化缓存配置
  91. initStorage() {
  92. this.storageList = []
  93. const storage = window.localStorage.getItem(this.storageName)
  94. // 不管是否初次还是要做一下处理,万一页面有修改,做一下更新,以最新的node节点数组为准
  95. let list = storage ? JSON.parse(storage) : []
  96. this.$vnode.componentOptions.children.forEach(node => {
  97. // 以label为准,因为可能会改文本
  98. if (!node.componentOptions.propsData.type && list.findIndex(i => i.label === node.componentOptions.propsData.label) < 0) {
  99. // 不是特殊类型的 找不到就加上
  100. const propsData = JSON.parse(JSON.stringify(node.componentOptions.propsData))
  101. propsData.fixed = propsData.fixed !== undefined ? 'left' : false
  102. list.push({
  103. fixed: false, // 默认新增的都是不固定
  104. show: true, // 默认新增的都是显示的
  105. ...propsData
  106. })
  107. }
  108. })
  109. // 必须在节点数组存在的才有意义
  110. list = list.filter(item => this.$vnode.componentOptions.children.find(n => {
  111. return item.label === n.componentOptions.propsData.label
  112. }))
  113. this.storageList = list
  114. },
  115. // 根据缓存的数组进行渲染表格
  116. updateTable() {
  117. const childrenNodes = this.$vnode.componentOptions.children.filter(node => node.componentOptions.propsData.type)
  118. this.storageList.forEach(item => {
  119. if (item.show) {
  120. const node = this.$vnode.componentOptions.children.find(n => n.componentOptions.propsData.label === item.label)
  121. if (node) {
  122. node.componentOptions.propsData.fixed = item.fixed
  123. childrenNodes.push(node)
  124. }
  125. }
  126. })
  127. this.config.children = childrenNodes
  128. this.config.attrs = this.$attrs
  129. this.config.listeners = this.$listeners
  130. this.showTable = false
  131. this.$nextTick(() => {
  132. this.showTable = true
  133. })
  134. window.localStorage.setItem(this.storageName, JSON.stringify(this.storageList))
  135. }
  136. }
  137. }
  138. </script>
  139. <style lang="scss" scoped>
  140. .table-cloumn-setting-popper{
  141. .setting-row-content{
  142. max-height: 600px;
  143. overflow-y: auto;
  144. .setting-row{
  145. height: 40px;
  146. line-height: 40px;
  147. .el-icon-s-operation{
  148. cursor: move;
  149. font-size: 16px;
  150. margin-right: 8px;
  151. }
  152. .label{
  153. margin-right: 8px;
  154. }
  155. .btn{
  156. padding: 4px!important;
  157. }
  158. }
  159. }
  160. }
  161. .hf-table{
  162. width:100%;
  163. height:100%;
  164. position: relative;
  165. .el-icon-setting{
  166. position: absolute;
  167. right: 20px;
  168. top:-20px;
  169. cursor: pointer;
  170. }
  171. }
  172. </style>

表格函数式组件

  1. import Vue from 'vue'
  2. export default Vue.component('newtable', {
  3. functional: true,
  4. props: {},
  5. listeners: {},
  6. render: function(h, context) {
  7. return h(
  8. 'el-table',
  9. {
  10. props: context.data.attrs.config.attrs,
  11. on: context.data.attrs.config.listeners
  12. },
  13. context.data.attrs.config.children
  14. )
  15. }
  16. })

问题点与优化

当真的推行到项目中时,发现了以上代码存在了几个问题:

1.函数式组件没有生命周期和实例,也就是table.js帮我们渲染了el-table,我们却没办法拿到el-table 的实例,也就没办法去调用table原生的方法,例如clearSelection等

2.忘了做插槽传递。例如空数据自定义插槽等

hf-table.vue

  1. <template>
  2. <div class="hf-table">
  3. <el-popover
  4. placement="bottom-end"
  5. popper-class="table-cloumn-setting-popper"
  6. trigger="click"
  7. >
  8. <div class="setting-row-content">
  9. <div style="text-align:right">
  10. <el-button @click="delAllStorage">恢复系统表格设置</el-button>
  11. <el-button @click="delStorage">恢复当前表格设置</el-button>
  12. </div>
  13. <draggable v-model="storageList" handle=".el-icon-s-operation" @end="updateTable">
  14. <div v-for="clo in storageList" :key="clo.label" class="setting-row">
  15. <i class="el-icon-s-operation" />
  16. <el-checkbox v-model="clo.show" class="label" @change="showOrHidden($event,clo)">{{ clo.label }}</el-checkbox>
  17. <el-button
  18. class="btn"
  19. size="mini"
  20. :type="clo.fixed === 'left' ? 'primary' : 'default'"
  21. @click="setFixed('left',clo)"
  22. >固定在左侧</el-button>
  23. <el-button
  24. class="btn"
  25. size="mini"
  26. :type="clo.fixed === 'right' ? 'primary' : 'default'"
  27. @click="setFixed('right',clo)"
  28. >固定在右侧</el-button>
  29. </div>
  30. </draggable>
  31. </div>
  32. <i slot="reference" class="el-icon-setting" />
  33. </el-popover>
  34. <!-- 按钮容器 -->
  35. <div
  36. class="table-operate-btn-content"
  37. >
  38. <!-- 插槽自定义表格上方操作栏 -->
  39. <slot name="operateBtnContent">
  40. <!-- 默认左右都有操作按钮,如果单纯想左或者想右,请在插入具名插槽 -->
  41. <div class="operate-btn-content">
  42. <!-- 流式左右布局 -->
  43. <slot name="btnContentLeft">
  44. <div />
  45. </slot>
  46. <slot name="btnContentRight">
  47. <div />
  48. </slot>
  49. </div>
  50. </slot>
  51. </div>
  52. <div :style="{height:`${tableHeight}px`}">
  53. <new-table v-if="showTable" :config="config" />
  54. </div>
  55. </div>
  56. </template>
  57. <script>
  58. import draggable from 'vuedraggable'
  59. import newTable from './table.js'
  60. import setHeight from '@/mixins/setHeight'
  61. const components = { newTable, draggable }
  62. export default {
  63. name: 'HfTable',
  64. components,
  65. mixins: [setHeight],
  66. props: {
  67. storageName: {
  68. type: String,
  69. required: true
  70. }
  71. },
  72. data() {
  73. return {
  74. showTable: false,
  75. storageList: [],
  76. name: '',
  77. config: {
  78. children: [],
  79. attrs: {},
  80. listeners: {}
  81. }
  82. }
  83. },
  84. watch: {
  85. '$attrs': {
  86. handler(newV) {
  87. this.$set(this.config, 'attrs', newV)
  88. },
  89. deep: true,
  90. immediate: true
  91. }
  92. },
  93. mounted() {
  94. this.initStorage()
  95. this.updateTable()
  96. },
  97. methods: {
  98. getInstance() {
  99. const ref = this.$children.find(i => i.$options._componentTag === 'el-table')
  100. return ref
  101. },
  102. delStorage() {
  103. this.$confirm('恢复当前表格设置将清除当前表格设置并刷新页面是否继续?', '提示', {
  104. confirmButtonText: '确定',
  105. cancelButtonText: '取消',
  106. type: 'warning'
  107. }).then(() => {
  108. const storage = window.localStorage.getItem('tableStorage') ? JSON.parse(window.localStorage.getItem('tableStorage')) : {}
  109. storage[this.storageName] = []
  110. window.localStorage.setItem('tableStorage', JSON.stringify(storage))
  111. location.reload()
  112. })
  113. },
  114. delAllStorage() {
  115. this.$confirm('恢复系统表格设置将清除当前表格设置并刷新页面是否继续?', '提示', {
  116. confirmButtonText: '确定',
  117. cancelButtonText: '取消',
  118. type: 'warning'
  119. }).then(() => {
  120. window.localStorage.removeItem('tableStorage')
  121. location.reload()
  122. })
  123. },
  124. showOrHidden(val, clo) {
  125. if (!val && this.storageList.filter(i => i.show).length === 0) {
  126. this.$message.warning('列表最少显示一列')
  127. this.$nextTick(() => {
  128. clo.show = true
  129. })
  130. return
  131. }
  132. this.updateTable()
  133. },
  134. setFixed(value, clo) {
  135. if (clo.fixed === value) {
  136. clo.fixed = false
  137. } else {
  138. clo.fixed = value
  139. }
  140. this.updateTable()
  141. },
  142. // 初始化缓存配置
  143. initStorage() {
  144. this.storageList = []
  145. const storage = window.localStorage.getItem('tableStorage') ? JSON.parse(window.localStorage.getItem('tableStorage')) : {}
  146. // 不管是否初次还是要做一下处理,万一页面有修改,做一下更新,以最新的node节点数组为准
  147. let list = storage[this.storageName] ? storage[this.storageName] : []
  148. this.$vnode.componentOptions.children.forEach(node => {
  149. // 以label为准,因为可能会改文本
  150. if (!(!node.componentOptions || node.componentOptions.propsData.type) && list.findIndex(i => i.label === node.componentOptions.propsData.label) < 0) {
  151. // 非插槽且 不是特殊类型的 找不到就加上
  152. const propsData = JSON.parse(JSON.stringify(node.componentOptions.propsData))
  153. if (propsData.fixed === undefined || propsData.fixed === false) {
  154. propsData.fixed = false
  155. } else {
  156. propsData.fixed = propsData.fixed ? propsData.fixed : 'left'
  157. }
  158. list.push({
  159. fixed: false, // 默认新增的都是不固定
  160. show: true, // 默认新增的都是显示的
  161. ...propsData
  162. })
  163. }
  164. })
  165. // 必须在节点数组存在的才有意义
  166. list = list.filter(item => this.$vnode.componentOptions.children.find(n => {
  167. return n.componentOptions && item.label === n.componentOptions.propsData.label
  168. }))
  169. this.storageList = list
  170. },
  171. // 根据缓存的数组进行渲染表格
  172. updateTable() {
  173. // 特殊类型
  174. const childrenNodes = this.$vnode.componentOptions.children.filter(node => node.componentOptions && node.componentOptions.propsData.type)
  175. this.storageList.forEach(item => {
  176. if (item.show) {
  177. const node = this.$vnode.componentOptions.children.find(n => n.componentOptions && n.componentOptions.propsData.label === item.label)
  178. if (node) {
  179. node.componentOptions.propsData.fixed = item.fixed
  180. childrenNodes.push(node)
  181. }
  182. }
  183. })
  184. this.config.children = childrenNodes
  185. this.config.attrs = this.$attrs
  186. this.config.listeners = this.$listeners
  187. this.showTable = false
  188. this.$nextTick(() => {
  189. this.showTable = true
  190. })
  191. const storage = window.localStorage.getItem('tableStorage') ? JSON.parse(window.localStorage.getItem('tableStorage')) : {}
  192. storage[this.storageName] = this.storageList
  193. window.localStorage.setItem('tableStorage', JSON.stringify(storage))
  194. }
  195. }
  196. }
  197. </script>
  198. <style lang="scss" scoped>
  199. .table-cloumn-setting-popper{
  200. .setting-row-content{
  201. max-height: 600px;
  202. overflow-y: auto;
  203. .setting-row{
  204. height: 40px;
  205. line-height: 40px;
  206. .el-icon-s-operation{
  207. cursor: move;
  208. font-size: 16px;
  209. margin-right: 8px;
  210. }
  211. .label{
  212. margin-right: 8px;
  213. }
  214. .btn{
  215. padding: 4px!important;
  216. }
  217. }
  218. }
  219. }
  220. .hf-table{
  221. width:100%;
  222. height:100%;
  223. position: relative;
  224. .el-icon-setting{
  225. position: absolute;
  226. right: 10px;
  227. top:16px;
  228. cursor: pointer;
  229. }
  230. .table-operate-btn-content{
  231. width: calc(100% - 40px);
  232. .operate-btn-content {
  233. height: 40px;
  234. display: flex;
  235. justify-content: space-between;
  236. align-items: center;
  237. }
  238. }
  239. }
  240. </style>

针对插槽的处理主要是根据插槽没有componentOption属性,然后把它和带有type的这类vnode直接丢给el-table,而其他的再去做显隐的处理。

table.js

  1. import Vue from 'vue'
  2. export default Vue.component('newtable', {
  3. functional: true,
  4. props: {},
  5. listeners: {},
  6. render: function(h, context) {
  7. const scopedSlots = {}
  8. Object.keys(context.parent.$scopedSlots).forEach(key => {
  9. if (key !== 'default') {
  10. scopedSlots[key] = context.parent.$scopedSlots[key]
  11. }
  12. })
  13. return context.parent.$createElement(
  14. 'el-table',
  15. {
  16. props: { ...context.data.attrs.config.attrs, ref: 'newtable' },
  17. on: context.data.attrs.config.listeners,
  18. attrs: { ref: 'newtable' },
  19. scopedSlots
  20. },
  21. context.data.attrs.config.children
  22. )
  23. }
  24. })

针对函数式组件没有实例的问题,这里我直接调用了父级组件的$createElement方法去创建el-table,再利用父级组件的children中‘children中`children中‘options._componentTag === 'el-table'`的vnode,来拿到对应的实例

有点奇怪的是我在创建的时候给生成的组件配置attrs的ref,在父组件中$refs无法拿到

还有一点要注意!我在控制组件重新渲染的时候,使用了$nexttick,所以不要在钩子函数中使用getInstance()方法获取表格组件实例,如果一定要,那就用链式判一下空再用this.$refs.hftable.getInstance()?.xxx()

后话

其实这是不是的合适方案也未定,但是最主要是过程中的一个探索吧。包括评论说的$slots去继承所有的vnode节点。其实在拿不到表格实例的时候我想换方案的时候尝试过这个办法,我直接去掉了函数式组件。直接写了一个el-table,然后具名插槽去接收。但是因为要操作vnode,也就是我要隐藏某列,这意味着我需要去修改hf-table中$slots中的default数组,就总觉得不太合适,共同进步吧~更多关于表格函数式组件封装element的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号