Vue3+Vuetify:点击表格行调用API显示通用Dialog实现指引
Vue3 + Vuetify 通用行详情Dialog实现方案
1. 封装通用Dialog组件
新建CommonRowDialog.vue,基于Vuetify Dialog封装,内置统一的API请求逻辑,支持跨页面复用:
<template> <v-dialog v-model="isDialogVisible" max-width="600px"> <v-card> <v-card-title> <span class="text-h5">行详情</span> </v-card-title> <v-card-text> <!-- 按需渲染行数据基础字段 --> <v-row> <v-col cols="12"> <span>ID: {{ rowData.id }}</span> </v-col> <v-col cols="12"> <span>名称: {{ rowData.name }}</span> </v-col> <!-- 其他字段根据实际结构添加 --> </v-row> <!-- API返回详情展示区域 --> <div v-if="loading" class="text-center mt-4">加载中...</div> <div v-else-if="detailData" class="mt-4"> <span>详情内容: {{ detailData.content }}</span> </div> </v-card-text> <v-card-actions> <v-btn @click="closeDialog" variant="outlined">关闭</v-btn> <v-btn @click="confirmAction" color="primary">确认</v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script setup> import { ref, watch } from 'vue' import axios from 'axios' const props = defineProps({ // 控制Dialog显隐 show: { type: Boolean, default: false }, // 点击的行数据 rowData: { type: Object, default: () => ({}) } }) const emit = defineEmits(['update:show', 'on-confirm']) const isDialogVisible = ref(props.show) const loading = ref(false) const detailData = ref(null) // 监听显隐状态,打开时自动请求详情 watch(() => props.show, (newVal) => { isDialogVisible.value = newVal if (newVal && props.rowData.id) { fetchRowDetail() } }) // 统一调用API获取详情 const fetchRowDetail = async () => { loading.value = true try { // 替换成你的统一API端点 const res = await axios.get(`/api/common/detail/${props.rowData.id}`) detailData.value = res.data } catch (err) { console.error('详情请求失败:', err) } finally { loading.value = false } } // 关闭Dialog并重置状态 const closeDialog = () => { emit('update:show', false) detailData.value = null } // 触发确认事件 const confirmAction = () => { emit('on-confirm', props.rowData) closeDialog() } </script>
2. 在页面中复用通用Dialog
以Vuetify DataTable为例,点击行时传递数据并打开Dialog:
<template> <v-container> <v-data-table :items="tableList" :headers="tableHeaders" @click:row="handleRowClick" ></v-data-table> <!-- 引入通用Dialog组件 --> <CommonRowDialog v-model:show="dialogVisible" :row-data="currentRow" @on-confirm="handleConfirm" /> </v-container> </template> <script setup> import { ref } from 'vue' import CommonRowDialog from './CommonRowDialog.vue' // 模拟表格表头和数据 const tableHeaders = [ { title: 'ID', key: 'id' }, { title: '名称', key: 'name' }, { title: '状态', key: 'status' } ] const tableList = ref([ { id: 1, name: '商品A', status: '正常' }, { id: 2, name: '商品B', status: '下架' } ]) const dialogVisible = ref(false) const currentRow = ref({}) // 表格行点击事件 const handleRowClick = (row) => { currentRow.value = row dialogVisible.value = true } // 处理Dialog确认操作 const handleConfirm = (row) => { console.log('确认操作,行数据:', row) // 可添加后续业务逻辑,比如提交修改、删除等 } </script>
核心要点
- 用
v-model:show实现父子组件的Dialog状态双向绑定,避免手动同步 - 通用组件内封装统一Axios请求,所有页面复用同一套API规则
- 打开Dialog时自动触发详情请求,减少页面重复代码
- 关闭Dialog时重置详情数据,避免旧内容残留
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

