iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > 其他 >vue3 table组件怎么使用
  • 377
分享到

vue3 table组件怎么使用

Vue3table 2023-05-14 23:05:40 377人浏览 独家记忆
摘要

基础表格首先开发table组件之前,先想好要用什么样式的api,因为笔者在生产工作中用的都是element,所以前面几个组件风格和element类似,但是这次不打算用element的风格了,打算换一种,直接展示:我们期望用户这样使用:<

基础表格

首先开发table组件之前,先想好要用什么样式的api,因为笔者在生产工作中用的都是element,所以前面几个组件风格和element类似,但是这次不打算用element的风格了,打算换一种,直接展示:
我们期望用户这样使用:

<script setup>
const dataList = [
  {
    id: 1,
    name: '《JavaEE企业应用实战》',
    author: 'dev1ce',
    price: '10.22',
    desc: '书中最后讲解的项目案例,涵盖从前期设计到最终实施的整个过程,对全书知识点进行串联和巩固,使读者融会贯通,掌握Java web开发的精髓。'
  },
  {
    id: 2,
    name: '《代码整洁之道》',
    author: 'R0bert',
    price: '10.22',
    desc: '整洁代码并非遵循一组规则编写的。不可能因为学习一套金规玉律就成为软件大师。专业精神和手工艺来自于推动规则形成的价值。'
  },
  {
    id: 3,
    name: '《ECMAScript 6 入门教程》',
    author: 'y1feng',
    price: '10.22',
    desc: '本书是一本开源javascript 语言教程,全面介绍 ECMAScript 6 新引入的语法特性。'
  },
]
const columnsList = [
  {
    title: '书名',
    key: 'name'
  },
  {
    title: '作者',
    key: 'author'
  },
  {
    title: '价格',
    key: 'price'
  },
  {
    title: '简介',
    key: 'desc'
  }
]
</script>
<template>
    <sanorin-table :columns="columnsList" :data="dataList"/>
</template>

依照这个写出以下代码

<script setup>
  import { ref, computed } from 'Vue'
  import { useProp, useNeumorphism } from '../mixin/neumorphism'
  const props = defineProps({
      ...useProp,
      ...{
        data: { // dataList
            type: Array,
            default: () => [],
        },
        columns: { // columnsList
            type: Array,
            default: () => [],
        },
      }
  })
  const { baseStyleObject } = useNeumorphism(props)
  let styleObject =  computed(() => ({ 
    // '--font-size': `${props.size-26}px`, '--line-height': `${props.size-20}px`, '--limit-size': `${props.size-28}px`
  }))
</script>
<template>
    <div :>
      <table >
        <thead>
          <tr class="neumorphism">
            <!-- 表头循环 -->
            <th v-for="col in columns" :key="col.key">{{col.title}}</th>
          </tr>
        </thead>
        <tbody>
          <!-- 表体循环 -->
          <tr class="neumorphism" v-for="row in data" :key="row.id">
            <td v-for="col in columns" :key="col.key">
              <span>
                {{row[col.key]}}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
</template>
<script>
  export default {
    name: 'sanorin-table',
  }
</script>
<style scoped>
  @import "../../style/index.CSS";
  @import "../../style/neumorphism.css";
  table {
    width: 100%;
    
    empty-cells: show;
    border-collapse:separate;
    border-spacing:0px 10px;
  }
  table td,
  table th {
    color: var(--text-color);
    padding: 8px 16px 8px 16px;
    text-align: left;
  }
  table th {
    color: var(--text-back-color) !important;
    font-weight: 600;
    white-space: nowrap;
  }
  table tr{
    margin-top: 20px;
  }
</style>

最后出来的效果就是:

vue3 table组件怎么使用

然后实现了这个后我们开始做后面的,先从固定表头开始。

固定表头

这里先采用第一种,以后不能满足需求了再改成后面的方法。
效果和代码如下:

vue3 table组件怎么使用

<script setup>
  import { ref, computed } from 'vue'
  import { useProp, useNeumorphism } from '../mixin/neumorphism'
  const props = defineProps({
      ...useProp,
      ...{
        data: { // dataList
            type: Array,
            default: () => [],
        },
        columns: { // columnsList
            type: Array,
            default: () => [],
        },
      }
  })
  const { baseStyleObject } = useNeumorphism(props)
  let styleObject =  computed(() => ({ 
  }))
</script>
<template>
    <div class="san-table scrollbar" :>
      <table>
        <thead>
            <tr class="neumorphism">
              <!-- 表头循环 -->
              <th v-for="col in columns" :key="col.key">{{col.title}}</th>
            </tr>
        </thead>
        <tbody>
          <!-- 表体循环 -->
          <tr class="neumorphism" v-for="row in data" :key="row.id">
            <td v-for="col in columns" :key="col.key">
              <span>
                {{row[col.key]}}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
</template>
<script>
  export default {
    name: 'sanorin-table',
  }
</script>
<style scoped>
  @import "../../style/index.css";
  @import "../../style/neumorphism.css";
  .san-table{
    padding: 0px 20px 20px 20px;
    height: 200px;
    position: relative;
    width: 700px;
    overflow: auto;
  }
  table {
    width: 100%;
    table-layout: fixed;
    empty-cells: show;
    border-collapse:separate;
    border-spacing:0px 10px;
  }
  thead {
    position: sticky;
    top: 10px;
  }
  thead:before{
    position: absolute;
    content: '';
    width: calc(100% + var(--shadow-blur) * 2);
    transfORM: translate(calc(var(--shadow-blur) * -1) , -10px);
    height: 20px;
    background-color: var(--main-color);
    z-index: -1;
  }
  table td,
  table th {
    color: var(--text-color);
    padding: 8px 16px 8px 16px;
    text-align: left;
  }
  table th {
    color: var(--text-back-color) !important;
    font-weight: 600;
    white-space: nowrap;
  }
</style>

高度/流体高度

可以为 Table 设置一个高度。(height)
当数据量动态变化时,可以为 Table 设置一个最大高度。(maxHeight) 通过设置max-height属性为 Table 指定最大高度。此时若表格所需的高度大于最大高度,则会显示一个滚动条。
只要在sanorin-table元素中定义了height或者maxHeight属性,即可实现固定表头的表格,而不需要额外的代码。
代码如下:

<script setup>
  import { ref, computed, Reactive } from 'vue'
  import { useProp, useNeumorphism } from '../mixin/neumorphism'
  const props = defineProps({
      ...useProp,
      ...{
        data: { // dataList
            type: Array,
            default: () => [],
        },
        columns: { // columnsList
            type: Array,
            default: () => [],
        },
        height: {
          type: Number,
        },
        maxHeight: {
          type: Number,
        }
      }
  })
  // 高度设置
  let tableHeightStyleObj = computed(() => { 
    let styleObj = ((e) => {
      if (e.maxHeight) return { maxHeight: e.maxHeight + 'px' }
      if (e.height) return { height: e.height + 'px' }
      return {}
    })({...props})
    return styleObj
  })
  const { baseStyleObject } = useNeumorphism(props)
  let styleObject =  computed(() => ({ 
    ...tableHeightStyleObj.value
  }))
</script>
<template>
    <div class="san-table scrollbar" :>
      <table>
        <colgroup>
            <col v-for="(col, index) in columns" :key="index">
        </colgroup>
        <thead>
            <tr class="neumorphism">
              <th v-for="col in columns" :key="col.key"> {{col.title}} </th>
            </tr>
        </thead>
        <tbody>
          <tr class="neumorphism" v-for="row in data" :key="row.id">
            <td v-for="col in columns" :key="col.key"> {{row[col.key]}} </td>
          </tr>
        </tbody>
      </table>
    </div>
</template>
<script>
  export default {
    name: 'sanorin-table',
  }
</script>
<style scoped>
  @import "../../style/index.css";
  @import "../../style/neumorphism.css";
  .san-table{
    padding: 0px 20px 20px 20px;
    position: relative;
    width: 700px;
    overflow: auto;
  }
  table {
    width: 100%;
    table-layout: fixed;
    empty-cells: show;
    border-collapse:separate;
    border-spacing:0px 10px;
  }
  thead {
    position: sticky;
    top: 10px;
  }
  thead:before{
    position: absolute;
    content: '';
    width: calc(100% + var(--shadow-blur) * 2);
    transform: translate(calc(var(--shadow-blur) * -1) , -10px);
    height: 20px;
    background-color: var(--main-color);
    z-index: -1;
  }
  table td,
  table th {
    color: var(--text-color);
    padding: 8px 16px 8px 16px;
    text-align: left;
  }
  table th {
    color: var(--text-back-color) !important;
    font-weight: 600;
    white-space: nowrap;
  }
</style>

自定义列宽

接下来加入宽度控制,希望在columns 传入的数组对象内加入宽度,示例如下:

const columnsList = [
  {
    title: '书名',
    key: 'name',
    width: 100,
  },
  {
    title: '作者',
    key: 'author',
    width: 100,
  },
  {
    title: '价格',
    key: 'price',
    width: 100,
  },
  {
    title: '简介',
    key: 'desc',
    minWidth: 350,
  }
]

希望达到以下效果
1、含有width的列,宽度固定,不随浏览器宽度变化而变化
2、含有minWidth的列,在大于设定值时,自动填充 table 剩余宽度,小于设定值时,固定该宽度
3、不包含width和minWidth的列,自动填充 table 剩余宽度
根据我们的需求,我们需要单独控制每一列的宽度展示,并在浏览器宽度变化时实时的重新计算并且重新渲染列。
首先定义出一个方法,用来计算每一列在当前情况下所要的宽度,再绑定要dom上。然后,每次表格变化/浏览器宽度变化时候就能实时响应改变Table的宽度了。

  const initColumns = () => {
    // 计算每一列在当前情况下所要的宽度
  }
  watch(() => props.columns, () => { initColumns() });
  onMounted(() => {
    nextTick(() => {
      initColumns();
      on(window, 'resize', throttle(() => initColumns(), 400));
    });
  });
  onBeforeUnmount(() => off(window, 'resize', () => initColumns()));

全部代码:

<script setup>
  import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
  import { on, off } from '../../utils/listener'
  import { throttle } from "../../utils/debounce&throttle"
  import { useProp, useNeumorphism } from '../mixin/neumorphism'
  const table = ref() // 与html中ref=""对应,定位dom元素
  const props = defineProps({
      ...useProp,
      ...{
        data: { // dataList
            type: Array,
            default: () => [],
        },
        columns: { // columnsList
            type: Array,
            default: () => [],
        },
        height: { // height
          type: Number,
        },
        maxHeight: { // 流体高度
          type: Number,
        },
        minUnsetWidth: {  // 未设置宽度时最小宽度
          type: Number,
          default: 80
        }
      }
  })
  // 高度设置
  let tableHeightStyleObj = computed(() => { 
    let styleObj = ((e) => {
      if (e.maxHeight) return { maxHeight: e.maxHeight + 'px' }
      if (e.height) return { height: e.height + 'px' }
      return {}
    })({...props})
    return styleObj
  })
  // 列宽设置
  let col = ref([])
  const { columns, minUnsetWidth } = props
  const _min_column_width = minUnsetWidth // 未设置宽度时最小宽度
  const initColumns = () => {
    col.value = (() => {
      let _total_width = table.value.offsetWidth  // 表格dom元素总宽度
      let _needed_minWidth = columns.reduce((t, v) => { // 需要的最小宽度
        t += v.width || v.minWidth || _min_column_width
        return t
      }, 0)
      // 需要的最小宽度比总宽度大,则取minWidth即可
      if (_needed_minWidth >= _total_width) return columns.reduce((t, v) => {
        let n = v.width || v.minWidth || _min_column_width
        t = [...t, n]
        return t
      }, [])
      // 需要的最小宽度比总宽度大,则要把minWidth加权,权重为(未分配的宽度 / minWidth之和)
      let _unassigned_width = columns.reduce((t, v) => {
        t += v.minWidth || 0
        return t
      }, 0)
      let _assigned_width = _needed_minWidth - _unassigned_width
      let _width_power = (_total_width - _assigned_width) / _unassigned_width
      return columns.reduce((t, v) => {
        let n = v.width || (v.minWidth ? (_width_power * v.minWidth).toFixed(2) : _min_column_width)
        t = [...t, n]
        return t
      }, [])
    })()
  }
  watch(() => props.columns, () => { initColumns() })
  const throttleInitColumns = () => throttle(() => initColumns(), 400)
  onMounted(() => {
    nextTick(() => {
      initColumns()
      on(window, 'resize', throttleInitColumns)
    })
  })
  onBeforeUnmount(() => off(window, 'resize', throttleInitColumns))
  const { baseStyleObject } = useNeumorphism(props)
  let styleObject =  computed(() => ({ 
    ...tableHeightStyleObj.value
  }))
</script>
<template>
    <div class="san-table scrollbar" :>
      <table ref="table">
        <colgroup>
            <col v-for="(item, index) in col" :key="index" :width="`${item}px`">
        </colgroup>
        <thead>
            <tr class="neumorphism">
              <th v-for="col in columns" :key="col.key"> {{col.title}} </th>
            </tr>
        </thead>
        <tbody>
          <tr class="neumorphism" v-for="row in data" :key="row.id">
            <td v-for="col in columns" :key="col.key"> {{row[col.key]}} </td>
          </tr>
        </tbody>
      </table>
    </div>
</template>
<script>
  export default {
    name: 'sanorin-table',
  }
</script>
<style scoped>
  @import "../../style/index.css";
  @import "../../style/neumorphism.css";
  .san-table{
    padding: 0px 20px 20px 20px;
    position: relative;
    overflow: auto;
  }
  table {
    width: 100%;
    table-layout: fixed;
    empty-cells: show;
    border-collapse:separate;
    border-spacing:0px 10px;
  }
  thead {
    position: sticky;
    top: 10px;
  }
  thead:before{
    position: absolute;
    content: '';
    width: calc(100% + var(--shadow-blur) * 2);
    transform: translate(calc(var(--shadow-blur) * -1) , -10px);
    height: 20px;
    background-color: var(--main-color);
    z-index: -1;
  }
  table td,
  table th {
    color: var(--text-color);
    padding: 8px 16px 8px 16px;
    text-align: left;
    Word-break:break-all;
  }
  table th {
    color: var(--text-back-color) !important;
    font-weight: 600;
    white-space: nowrap;
  }
</style>

其中用到的两个js,防抖节流和注册监听这里也放下吧


let timeout = null // 创建一个标记用来存放定时器的返回值
let count = 0;
export function debounce(fn, wait = 1000, immediate = false) {
  return function () {
    const args = arguments;
    if (immediate) {
      if (count == 0) {
        fn.apply(this, arguments)
        count++;
      } else {
        if (timeout) {
          clearTimeout(timeout) // 每当用户输入的时候把前一个 setTimeout clear 掉 
        }
        timeout = setTimeout(() => {
          fn.apply(this, arguments)
        }, wait)
      }
    } else {
      if (timeout) {
        clearTimeout(timeout) // 每当用户输入的时候把前一个 setTimeout clear 掉 
      }
      timeout = setTimeout(() => {
        fn.apply(this, arguments)
      }, wait)
    }
  }()
}
let canRun = true;
let count1 = 0;
export function throttle(fn, wait = 1000, immediate = true) {
  return function () {
    if (immediate) {
      if (count1 == 0) {
        fn.apply(this, arguments);
        count1++;
      } else {
        if (canRun) {
          canRun = false
          setTimeout(function () {
            fn.apply(this, arguments)
            canRun = true
          }, wait);
        }
      }
    } else {
      if (!canRun) return
      canRun = false
      setTimeout(function () {
        fn.apply(this, arguments)
        canRun = true
      }, wait);
    }
  }()
}

export const on = (element, event, handler) => {
  if (document.addEventListener) {
    if (element && event && handler) {
      element.addEventListener(event, handler, false)
    }
  }
}

export const off = (element, event, handler) => {
  if (document.removeEventListener) {
    if (element && event) {
      element.removeEventListener(event, handler, false)
    }
  }
}

以上就是vue3 table组件怎么使用的详细内容,更多请关注编程网其它相关文章!

--结束END--

本文标题: vue3 table组件怎么使用

本文链接: https://www.lsjlt.com/news/208259.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • vue3 table组件怎么使用
    基础表格首先开发table组件之前,先想好要用什么样式的api,因为笔者在生产工作中用的都是element,所以前面几个组件风格和element类似,但是这次不打算用element的风格了,打算换一种,直接展示:我们期望用户这样使用:<...
    99+
    2023-05-14
    Vue3 table
  • vue3 table组件如何使用
    今天小编给大家分享一下vue3 table组件如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。基础表格首先开发tabl...
    99+
    2023-07-06
  • Vue3 table表格组件的使用
    目录一、Ant Design Vue1、官网地址2、怎么使用3、将电子书表格进行展示二、总结一、Ant Design Vue 在大量数据需要展示时,我们一般都会以报表的形式展现,按照...
    99+
    2024-04-02
  • Vue3复用组件怎么使用
    我们看到,createReusableTemplate 返回了一个 Tuple,即 define 和 reuse 的组件对,然后,通过上面的例子就可以在单文件里面复用多处代码了。还有,实际上还可以通过对象解构的方式返回一个 define 和...
    99+
    2023-05-20
    Vue3
  • vue3动态组件怎么使用
    这篇文章主要介绍“vue3动态组件怎么使用”,在日常操作中,相信很多人在vue3动态组件怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”vue3动态组件怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来...
    99+
    2023-07-06
  • Vue3之Teleport组件怎么使用
    Teleport 组件解决的问题版本:3.2.31如果要实现一个 “蒙层” 的功能,并且该 “蒙层” 可以遮挡页面上的所有元素,通常情况下我们会选择直接在 标签下渲染 “蒙层” 内容。如果在Vue.js 2 中实现这个功能,只能通过原生 D...
    99+
    2023-05-14
    Vue3 teleport
  • Vue3异步组件Suspense怎么使用
    今天小编给大家分享一下Vue3异步组件Suspense怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。Suspense...
    99+
    2023-07-06
  • Layui table组件怎么用
    这篇文章主要介绍“Layui table组件怎么用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Layui table组件怎么用”文章能帮助大家解决问题。   出...
    99+
    2024-04-02
  • Vue3怎么使用Vite打包组件库
    本文小编为大家详细介绍“Vue3怎么使用Vite打包组件库”,内容详细,步骤清晰,细节处理妥当,希望这篇“Vue3怎么使用Vite打包组件库”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。打包配置vite 专门提供...
    99+
    2023-07-05
  • vue3伸缩菜单组件怎么使用
    本篇内容介绍了“vue3伸缩菜单组件怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!效果图在components下面创建一个conta...
    99+
    2023-07-05
  • vue3异步组件怎么用
    这篇文章给大家分享的是有关vue3异步组件怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。 在vue3中,异步组件可以减少打包的结果,会将异步组件...
    99+
    2024-04-02
  • Vue3中的异步组件defineAsyncComponentAPI怎么使用
    传递工厂函数作为参数defineAsyncComponent方法接收一个工厂函数是它的基本用法,这个工厂函数必须返回一个Promise,Promise的resolve应该返回一个组件。我们这里以Vue Cli创建的项目为例,这里我稍微做了一...
    99+
    2023-05-21
    Vue3
  • Vue3 Element Plus el-form表单组件怎么使用
    在 Element Plus 中,el-form 是一个表单组件,用于创建表单以便用户填写和提交数据。它提供了许多内置的验证规则和验证方法,使表单验证更加容易。使用 el-form 组件,您可以将表单控件组织在一起,并对表单进行验证,以确保...
    99+
    2023-05-14
    Vue3 element plus el-form
  • vue3动态加载组件及动态引入组件怎么使用
    本篇内容介绍了“vue3动态加载组件及动态引入组件怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1.问题在做一个用vite构建的vu...
    99+
    2023-07-05
  • Vue3怎么封装组件
    这篇文章主要讲解了“Vue3怎么封装组件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Vue3怎么封装组件”吧!例如我们在使用element的标签页tabs组件时,如下图所示:tabs组件可...
    99+
    2023-07-05
  • vue3动态组件使用详解
    目录vue2vue3markRow:标记一个对象,使其不能成为一个响应式对象。toRaw:将响应式对象(由 reactive定义的响应式)转换为普通对象。shallowRef:只处理...
    99+
    2023-02-27
    vue3中动态组件 vue3动态加载组件 vue3动态添加组件
  • Vue3之Teleport组件如何使用
    这篇文章主要介绍了Vue3之Teleport组件如何使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Vue3之Teleport组件如何使用文章都会有所收获,下面我们一起来看看吧。Teleport 组件解决的问...
    99+
    2023-07-06
  • Vue3全局组件通信之provide/inject怎么使用
    本篇内容介绍了“Vue3全局组件通信之provide/inject怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1、前言顾名思义,爷...
    99+
    2023-07-06
  • vue3无限滚动组件怎么用
    这篇“vue3无限滚动组件怎么用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“vue3无限滚动组件怎么用”文章吧。什么是无限...
    99+
    2023-06-29
  • vue3动态组件如何使用
    这篇“vue3动态组件如何使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“vue3动态组件如何使用”文章吧。问题:为什么v...
    99+
    2023-07-05
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作