Bootstrap

Vue3的原生table导出及父组件调用子组件中的方法

1、安装依赖(xlsx版本高于0.18)

npm install xlsx fs

2、创建子组件,标签添加ref属性,用于获取该元素el

<template>
	<table id="previewTable" ref="exportPreviewTableRef"></table>
</template>
<script setup name="previewTable">
//导入xlsx包文件
import * as XLSX from "xlsx/xlsx.mjs"

//获取Vue实列
const { proxy } = getCurrentInstance()

//父组件给子组件传值,通过Props
const props = defineProps({
	programmeId: {
		type: String,
		default: ""
	}
})

//监听
watch(
	() => props.programmeId,
	(newVal, oldValue) => {
		loadPreview(newVal)
	},
	{
		immediate: true,
		deep: true
	}
)

//加载table表格
function loadPreview(programmeId) { }

//导出table
const exportPreviewTable = () => {
    //根据ref获取table的el
	var table_elt = proxy.$refs['exportPreviewTableRef']

	// Extract Data (create a workbook object from the table)
	var workbook = XLSX.utils.table_to_book(table_elt)

	// Process Data (add a new row)
	var ws = workbook.Sheets["模板"]
	XLSX.utils.sheet_add_aoa(ws, [], {
		origin: -1,
	})

	// Package and Release Data ('writeFile' tries to write and save an XLSX file)
	XLSX.writeFile(workbook, "回传模板.xlsx")
}

//定义暴露,将属性和方法,必须有,否则父组件找不到方法
defineExpose({
	exportPreviewTable
});
</script>

//定义table样式
<style type="text/css">
#previewTable {
	border-collapse: collapse;
	width: 100%;
}

#previewTable tr td {
	border: 1px solid;
	width: 80px;
}
</style>

3、父组件调用子组件方法

<template>
	<div class="app-container">
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" @click="exportTable">导出</el-button>
			</el-col>
		</el-row>
		<!-- 子组件 -->
		<previewTable v-model:programmeId=previewProgrammeId ref="childRef"></previewTable>
	</div>
</template>
<script setup name="shipmentIndex">
//导入子组件
import previewTable from '@/views/components/preview/previewTable'

//获取唯一Vue实列
const { proxy } = getCurrentInstance()

//传给子组件的值
const previewProgrammeId = ref('')

//定义一个ref类型的变量,变量名必须与子组件的ref参数同名,相当于绑定了子组件
const childRef = ref(null)

//父组件导出按钮调用子组件方法导出
function exportTable() {
	childRef.value.exportPreviewTable()
}
</script>

;