表格封装~

对表格复用的查询、重置、分页等方法进行抽取封装hooks

封装 hooks:

import { ref, reactive, onMounted } from 'vue'
// 表格通用代码抽取hook,具体用法参考财务管理-发票台账或者合同管理-合同台账
export default function () {
	// 搜索按钮加载
	const searchLoading = ref(false)
	// 重置按钮加载
	const resetLoading = ref(false)
	// 表格高度
	const height = ref(500)
	// 表格加载标志
	const tableLoading = ref(false)
	// 分页数据
	const pagination = reactive({
		current: 1,
		total: 0,
		size: 20,
	})
	onMounted(() => {
		// 根据表格上方的el-form行数,动态减取高度,换行请使用el-form包裹
		const line = document.querySelectorAll('.el-form').length
		height.value = window.innerHeight - (280 + (line - 1) * 45)
	})
	// 搜索
	const handleSearch = (getData: () => void) => {
		searchLoading.value = true
		pagination.current = 1
		getData()
	}
	// 重置
	const handleReset = (queryParam: any, getData: () => void) => {
		resetLoading.value = true
		pagination.size = 20
		pagination.current = 1
		// ------只适用全部重置为空字符串的场景--------
		const keys = Object.keys(queryParam)
		const obj: { [proName: string]: string } = {}
		keys.forEach((item) => {
			obj[item] = ''
		})
		Object.assign(queryParam, obj)
		getData()
	}
	// 改变每页条数
	const handleSizeChange = (val: number, getData: () => void) => {
		pagination.size = val
		getData()
	}

	// 改变页数
	const handleCurrentChange = (val: number, getData: () => void) => {
		pagination.current = val
		getData()
	}
	// 表格行样式控制
	const tableRowClassName = ({ rowIndex }: any) => {
		if (rowIndex % 2 == 0) {
			return 'warning-row'
		} else {
			return 'success-row'
		}
	}
	const returnObj = {
		searchLoading,
		resetLoading,
		height,
		pagination,
		tableLoading,
		handleSearch,
		handleReset,
		tableRowClassName,
		handleSizeChange,
		handleCurrentChange,
	}
	return returnObj
}

页面中使用:

import useTableCode from '@/hooks/useTableCode'	

   const {
		searchLoading,
		resetLoading,
		height,
		pagination,
		tableLoading,
		handleSearch,
		handleReset,
		tableRowClassName,
		handleSizeChange,
		handleCurrentChange,
	} = useTableCode()


你可能感兴趣的:(vue.js,javascript,前端)