首頁  >  文章  >  web前端  >  如何用Vue3實作可複製表格

如何用Vue3實作可複製表格

WBOY
WBOY轉載
2023-05-11 20:19:121615瀏覽

最基礎的表格封裝

最基礎基礎的表格封裝所要做的事情就是讓使用者只專注於行和列的數據,而不需要關注DOM 結構是怎樣的,我們可以參考AntDesigncolumns 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(&#39;copy&#39;)
    }
    
    // 将复制方法暴露出去以供父组件可以直接调用
    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(&#39;copy&#39;)
        
        // 别忘了把状态重置回来
        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 &#39;vue&#39;
import { Table as CTable } from &#39;../components&#39;
import arrowUpIcon from &#39;../assets/arrow-up.svg&#39;

const columns = [
  { title: &#39;序号&#39;, dataIndex: &#39;serial&#39; },
  { title: &#39;班级&#39;, dataIndex: &#39;class&#39; },
  { title: &#39;姓名&#39;, dataIndex: &#39;name&#39; },
  { title: &#39;状态&#39;, dataIndex: &#39;status&#39;, slotName: &#39;status&#39;, slotNameOnCopy: &#39;statusOnCopy&#39; }
]

const dataSource = [
  { serial: 1, class: &#39;三年级1班&#39;, name: &#39;张三&#39; },
  { serial: 2, class: &#39;三年级2班&#39;, name: &#39;李四&#39; },
  { serial: 3, class: &#39;三年级3班&#39;, name: &#39;王五&#39; },
  { serial: 4, class: &#39;三年级4班&#39;, name: &#39;赵六&#39; },
  { serial: 5, class: &#39;三年级5班&#39;, name: &#39;宋江&#39; },
  { serial: 6, class: &#39;三年级6班&#39;, name: &#39;卢俊义&#39; },
  { serial: 7, class: &#39;三年级7班&#39;, name: &#39;吴用&#39; },
  { serial: 8, class: &#39;三年级8班&#39;, name: &#39;公孙胜&#39; },
]

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 &#39;vue&#39;
import type { PropType } from &#39;vue&#39;

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(&#39;copy&#39;)
        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中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除