最基础的表格封装
最基础基础的表格封装所要做的事情就是让用户只关注行和列的数据,而不需要关注 DOM
结构是怎样的,我们可以参考 AntDesign
,columns
dataSource
这两个属性是必不可少的,代码如下:
import { defineComponent } from 'vue' import type { PropType } from 'vue' interface Column { title: string; dataIndex: string; slotName?: string; } type TableRecord = Record<string, unknown>; export const Table = defineComponent({ props: { columns: { type: Array as PropType<Column[]>, required: true, }, dataSource: { type: Array as PropType<TableRecord[]>, default: () => [], }, rowKey: { type: Function as PropType<(record: TableRecord) => string>, } }, setup(props, { slots }) { const getRowKey = (record: TableRecord, index: number) => { if (props.rowKey) { return props.rowKey(record) } return record.id ? String(record.id) : String(index) } const getTdContent = ( text: any, record: TableRecord, index: number, slotName?: string ) => { if (slotName) { return slots[slotName]?.(text, record, index) } return text } return () => { return ( <table> <tr> {props.columns.map(column => { const { title, dataIndex } = column return <th key={dataIndex}>{title}</th> })} </tr> {props.dataSource.map((record, index) => { return ( <tr key={getRowKey(record, index)}> {props.columns.map((column, i) => { const { dataIndex, slotName } = column const text = record[dataIndex] return ( <td key={dataIndex}> {getTdContent(text, record, i, slotName)} </td> ) })} </tr> ) })} </table> ) } } })
需要关注一下的是 Column
中有一个 slotName
属性,这是为了能够自定义该列的所需要渲染的内容(在 AntDesign
中是通过 TableColumn
组件实现的,这里为了方便直接使用 slotName
)。
实现复制功能
首先我们可以手动选中表格复制尝试一下,发现表格是支持选中复制的,那么实现思路也就很简单了,通过代码选中表格再执行复制命令就可以了,代码如下:
export const Table = defineComponent({ props: { // ... }, setup(props, { slots, expose }) { // 新增,存储table节点 const tableRef = ref<HTMLTableElement | null>(null) // ... // 复制的核心方法 const copy = () => { if (!tableRef.value) return const range = document.createRange() range.selectNode(tableRef.value) const selection = window.getSelection() if (!selection) return if (selection.rangeCount > 0) { selection.removeAllRanges() } selection.addRange(range) document.execCommand('copy') } // 将复制方法暴露出去以供父组件可以直接调用 expose({ copy }) return (() => { return ( // ... ) }) as unknown as { copy: typeof copy } // 这里是为了让ts能够通过类型校验,否则调用`copy`方法ts会报错 } })
这样复制功能就完成了,外部是完全不需要关注如何复制的,只需要调用组件暴露出去的 copy
方法即可。
处理表格中的不可复制元素
虽然复制功能很简单,但是这也仅仅是复制文字,如果表格中有一些不可复制元素(如图片),而复制时需要将这些替换成对应的文字符号,这种该如何实现呢?
解决思路就是在组件内部定义一个复制状态,调用复制方法时把状态设置为正在复制,根据这个状态渲染不同的内容(非复制状态时渲染图片,复制状态是渲染对应的文字符号),代码如下:
export const Table = defineComponent({ props: { // ... }, setup(props, { slots, expose }) { const tableRef = ref<HTMLTableElement | null>(null) // 新增,定义复制状态 const copying = ref(false) // ... const getTdContent = ( text: any, record: TableRecord, index: number, slotName?: string, slotNameOnCopy?: string ) => { // 如果处于复制状态,则渲染复制状态下的内容 if (copying.value && slotNameOnCopy) { return slots[slotNameOnCopy]?.(text, record, index) } if (slotName) { return slots[slotName]?.(text, record, index) } return text } const copy = () => { copying.value = true // 将复制行为放到 nextTick 保证复制到正确的内容 nextTick(() => { if (!tableRef.value) return const range = document.createRange() range.selectNode(tableRef.value) const selection = window.getSelection() if (!selection) return if (selection.rangeCount > 0) { selection.removeAllRanges() } selection.addRange(range) document.execCommand('copy') // 别忘了把状态重置回来 copying.value = false }) } expose({ copy }) return (() => { return ( // ... ) }) as unknown as { copy: typeof copy } } })
测试
最后我们可以写一个demo测一下功能是否正常,代码如下:
<template> <button @click="handleCopy">点击按钮复制表格</button> <c-table :columns="columns" :data-source="dataSource" border="1" ref="table" > <template #status> <img class="status-icon" :src="arrowUpIcon" /> </template> <template #statusOnCopy> → </template> </c-table> </template> <script setup lang="ts"> import { ref } from 'vue' import { Table as CTable } from '../components' import arrowUpIcon from '../assets/arrow-up.svg' const columns = [ { title: '序号', dataIndex: 'serial' }, { title: '班级', dataIndex: 'class' }, { title: '姓名', dataIndex: 'name' }, { title: '状态', dataIndex: 'status', slotName: 'status', slotNameOnCopy: 'statusOnCopy' } ] const dataSource = [ { serial: 1, class: '三年级1班', name: '张三' }, { serial: 2, class: '三年级2班', name: '李四' }, { serial: 3, class: '三年级3班', name: '王五' }, { serial: 4, class: '三年级4班', name: '赵六' }, { serial: 5, class: '三年级5班', name: '宋江' }, { serial: 6, class: '三年级6班', name: '卢俊义' }, { serial: 7, class: '三年级7班', name: '吴用' }, { serial: 8, class: '三年级8班', name: '公孙胜' }, ] const table = ref<InstanceType<typeof CTable> | null>(null) const handleCopy = () => { table.value?.copy() } </script> <style scoped> .status-icon { width: 20px; height: 20px; } </style>
附上完整代码:
import { defineComponent, ref, nextTick } from 'vue' import type { PropType } from 'vue' interface Column { title: string; dataIndex: string; slotName?: string; slotNameOnCopy?: string; } type TableRecord = Record<string, unknown>; export const Table = defineComponent({ props: { columns: { type: Array as PropType<Column[]>, required: true, }, dataSource: { type: Array as PropType<TableRecord[]>, default: () => [], }, rowKey: { type: Function as PropType<(record: TableRecord) => string>, } }, setup(props, { slots, expose }) { const tableRef = ref<HTMLTableElement | null>(null) const copying = ref(false) const getRowKey = (record: TableRecord, index: number) => { if (props.rowKey) { return props.rowKey(record) } return record.id ? String(record.id) : String(index) } const getTdContent = ( text: any, record: TableRecord, index: number, slotName?: string, slotNameOnCopy?: string ) => { if (copying.value && slotNameOnCopy) { return slots[slotNameOnCopy]?.(text, record, index) } if (slotName) { return slots[slotName]?.(text, record, index) } return text } const copy = () => { copying.value = true nextTick(() => { if (!tableRef.value) return const range = document.createRange() range.selectNode(tableRef.value) const selection = window.getSelection() if (!selection) return if (selection.rangeCount > 0) { selection.removeAllRanges() } selection.addRange(range) document.execCommand('copy') copying.value = false }) } expose({ copy }) return (() => { return ( <table ref={tableRef}> <tr> {props.columns.map(column => { const { title, dataIndex } = column return <th key={dataIndex}>{title}</th> })} </tr> {props.dataSource.map((record, index) => { return ( <tr key={getRowKey(record, index)}> {props.columns.map((column, i) => { const { dataIndex, slotName, slotNameOnCopy } = column const text = record[dataIndex] return ( <td key={dataIndex}> {getTdContent(text, record, i, slotName, slotNameOnCopy)} </td> ) })} </tr> ) })} </table> ) }) as unknown as { copy: typeof copy } } })
以上是如何用Vue3实现可复制表格的详细内容。更多信息请关注PHP中文网其他相关文章!

Vue.js与前端技术栈紧密集成,提升开发效率和用户体验。1)构建工具:与Webpack、Rollup集成,实现模块化开发。2)状态管理:与Vuex集成,管理复杂应用状态。3)路由:与VueRouter集成,实现单页面应用路由。4)CSS预处理器:支持Sass、Less,提升样式开发效率。

Netflix选择React来构建其用户界面,因为React的组件化设计和虚拟DOM机制能够高效处理复杂界面和频繁更新。1)组件化设计让Netflix将界面分解成可管理的小组件,提高了开发效率和代码可维护性。2)虚拟DOM机制通过最小化DOM操作,确保了Netflix用户界面的流畅性和高性能。

Vue.js被开发者喜爱因为它易于上手且功能强大。1)其响应式数据绑定系统自动更新视图。2)组件系统提高了代码的可重用性和可维护性。3)计算属性和侦听器增强了代码的可读性和性能。4)使用VueDevtools和检查控制台错误是常见的调试技巧。5)性能优化包括使用key属性、计算属性和keep-alive组件。6)最佳实践包括清晰的组件命名、使用单文件组件和合理使用生命周期钩子。

Vue.js是一个渐进式的JavaScript框架,适用于构建高效、可维护的前端应用。其关键特性包括:1.响应式数据绑定,2.组件化开发,3.虚拟DOM。通过这些特性,Vue.js简化了开发过程,提高了应用性能和可维护性,使其在现代Web开发中备受欢迎。

Vue.js和React各有优劣,选择取决于项目需求和团队情况。1)Vue.js适合小型项目和初学者,因其简洁和易上手;2)React适用于大型项目和复杂UI,因其丰富的生态系统和组件化设计。

Vue.js通过多种功能提升用户体验:1.响应式系统实现数据即时反馈;2.组件化开发提高代码复用性;3.VueRouter提供平滑导航;4.动态数据绑定和过渡动画增强交互效果;5.错误处理机制确保用户反馈;6.性能优化和最佳实践提升应用性能。

Vue.js在Web开发中的角色是作为一个渐进式JavaScript框架,简化开发过程并提高效率。1)它通过响应式数据绑定和组件化开发,使开发者能专注于业务逻辑。2)Vue.js的工作原理依赖于响应式系统和虚拟DOM,优化性能。3)实际项目中,使用Vuex管理全局状态和优化数据响应性是常见实践。

Vue.js是由尤雨溪在2014年发布的渐进式JavaScript框架,用于构建用户界面。它的核心优势包括:1.响应式数据绑定,数据变化自动更新视图;2.组件化开发,UI可拆分为独立、可复用的组件。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

Dreamweaver Mac版
视觉化网页开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

Atom编辑器mac版下载
最流行的的开源编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。