ag-grid vue3 入门教程,介绍ag-grid在vue3中的用法,包括事件的响应、获取选中值、自定义单元格组件。
npm install --save ag-grid-community
npm install --save ag-grid-vue3
import { AgGridVue } from "ag-grid-vue3";
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-balham.css";
<template>
<div class="pagex">
<!-- 使用ag-grid-vue组件 其中columnDefs为列,rowData为表格数据 -->
<ag-grid-vue
style="width: 80%; height: 200px;"
class="table ag-theme-balham"
:columnDefs="columnDefs"
:rowData="rowData"
:enableColResize="true"
:gridReady="onGridReady"
@cellClicked="onCellClicked"
></ag-grid-vue>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { AgGridVue } from "ag-grid-vue3";
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-balham.css";
/*
ag-grid 中文文档
https://www.itxst.com/ag-grid/tutorial.html
*/
const gridApi=ref(null);
const columnApi=ref(null);
const columnDefs=ref([
{headerName: '名称', field: 'title', checkboxSelection: true},
{headerName: '网址', field: 'url', width: 200},
{headerName: '分类', field: 'catalog'},
{headerName: 'PR', field: 'pr'}
]);
const rowData=ref([
{title: '谷歌', url: 'www.google', catalog: '搜索引擎',pr:10},
{title: '微软', url: 'www.microsoft.com', catalog: '操作系',pr:10},
{title: 'ITXST', url: 'www.itxst.com', catalog: '小站',pr:1},
{title: '淘宝', url: 'www.taobao.com', catalog: '电商',pr:8}
])
const onGridReady= (params) =>{
console.log(params);
// 获取gridApi
gridApi.value = params.api;
columnApi.value = params.columnApi;
// 这时就可以通过gridApi调用ag-grid的传统方法了
gridApi.value.sizeColumnsToFit();
}
const onCellClicked =(cell)=> {
console.log(cell);
// 获取选中单元格的数据
console.log(cell.value);
// 获取选中单元格所在行号
console.log(cell.rowIndex);
// 获取选中单元格所在行的数据
console.log(cell.data);
}
</script>
<style scoped lang="scss">
.pagex {
padding: 0px;
}
</style>
例子