Skip to content

页面视图开发 ​

说明

页面视图位于 src/views/ 目录,每个业务模块遵循 index.vue(列表页)+ edit.vue(编辑弹窗)的标准模式,辅以 columns.ts(列定义)和 querySchemas.ts(搜索表单)配置文件。

目录结构 ​

src/views/
├── system/
│ ├── position/
│ │ ├── index.vue       # 岗位列表页
│ │ ├── edit.vue        # 岗位编辑弹窗
│ │ ├── columns.ts      # 表格列定义
│ │ └── querySchemas.ts # 搜索表单定义
│ ├── user/
│ │ ├── index.vue
│ │ └── edit.vue
│ ├── role/
│ │ ├── index.vue
│ │ └── edit.vue
│ └── ...
├── cms/
│ ├── article/
│ └── ...
└── ...

文件职责 ​

文件职责说明
index.vue列表页搜索表单 + 工具栏 + BasicTable + 编辑弹窗引用
edit.vue编辑弹窗basicModal + n-form,懒加载
columns.ts表格列定义定义列 key、title、render 函数等
querySchemas.ts搜索表单定义FormSchema 数组,定义搜索字段

index.vue 列表页 ​

以岗位管理为例,完整结构如下:

vue
<!-- src/views/system/position/index.vue -->
<template>
  <div>
    <n-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :autoScrollX="true"
      >
        <template #tableTitle>
          <n-space>
            <n-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>
            <n-button
              type="error"
              @click="handleDelete"
              :disabled="!rowKeys.length"
              v-perm="['sys:position:batchDelete']"
            >
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <editDialog
      ref="createModalRef"
      :positionId="positionId"
      v-if="editVisible"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref, unref } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { getPositionList, positionDelete, positionBatchDelete } from '@/api/system/position';
  import { columns } from './columns';
  import { PlusOutlined, DeleteOutlined, FormOutlined } from '@vicons/antd';
  import editDialog from './edit.vue';
  import { schemas } from './querySchemas';
  import { renderIcon } from '@/utils';

  /**
   * 定义参数
   */
  const message = useMessage();
  const dialog = useDialog();
  const basicTableRef = ref();
  const createModalRef = ref();
  const editVisible = ref(false);
  const positionId = ref(0);
  const rowKeys = ref([]);

  /**
   * 定义查询参数
   */
  const formParams = reactive({
    name: '',
    status: '',
  });

  /**
   * 定义操作栏
   */
  const actionColumn = reactive({
    width: 200,
    title: '操作',
    align: 'center',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            icon: renderIcon(FormOutlined),
            type: 'info',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:position:update'],
          },
          {
            label: '删除',
            icon: renderIcon(DeleteOutlined),
            type: 'error',
            onClick: handleDelete.bind(null, record),
            auth: ['sys:position:delete'],
          },
        ],
      });
    },
  });

  /**
   * 加载数据列表
   */
  const loadDataTable = async (res) => {
    rowKeys.value = [];
    const result = await getPositionList({ ...formParams, ...res });
    return result;
  };

  /**
   * 数据行选择事件
   */
  function onCheckedRow(keys) {
    rowKeys.value = keys;
  }

  /**
   * 刷新数据列表
   */
  function reloadTable(noRefresh = '') {
    basicTableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  /**
   * 执行提交表单
   */
  function handleSubmit(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行重置
   */
  function handleReset(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行注册
   */
  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    positionId.value = 0;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };

  /**
   * 执行编辑
   */
  async function handleEdit(record: Recordable) {
    positionId.value = record.id;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  }

  /**
   * 执行删除
   */
  async function handleDelete(record) {
    dialog.warning({
      title: '提示',
      content: '确定要删除?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        record.id ? await positionDelete(record.id) : await positionBatchDelete(rowKeys.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }
</script>

edit.vue 编辑弹窗 ​

vue
<!-- src/views/system/position/edit.vue -->
<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form
        class="ls-form"
        ref="formRef"
        :model="formData"
        label-placement="left"
        label-width="85px"
      >
        <n-form-item
          label="岗位名称"
          path="name"
          :rule="{ required: true, message: '请输入岗位名称', trigger: 'blur' }"
        >
          <n-input v-model:value="formData.name" placeholder="请输入岗位名称" clearable />
        </n-form-item>
        <n-form-item label="岗位状态" path="code">
          <n-radio-group v-model:value="formData.status" name="status">
            <n-radio :value="1">正常</n-radio>
            <n-radio :value="2">停用</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number v-model:value="formData.sort" />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { getPositionDetail, positionAdd, positionUpdate } from '@/api/system/position';
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useModal } from '@/components/Modal';

  /**
   * 定义参数
   */
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();

  /**
   * 定义表单参数
   */
  const message = useMessage();
  const formData = reactive({
    id: '',
    name: '',
    status: 1,
    sort: 0,
  });

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    positionId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.positionId ? '编辑岗位' : '添加岗位',
    subBtuText: '确定',
    width: 600,
  });

  /**
   * 执行提交
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.positionId ? await positionUpdate(formData) : await positionAdd(formData);
        message.success('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getPositionDetail(props.positionId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    if (props.positionId) {
      setFormData();
    }
  });

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>

数据流 ​

页面加载 → BasicForm 注册 → BasicTable request 触发 → loadDataTable → API → 渲染表格
用户搜索 → handleSubmit → 更新 formParams → reloadTable → 重新请求
用户新增 → handleAdd → positionId=0 → editVisible=true → openModal() → 表单填写 → 提交
用户编辑 → handleEdit → positionId=id → editVisible=true → openModal() → 加载详情 → 修改 → 提交
用户删除 → dialog.warning → onPositiveClick → API → reloadTable

columns.ts ​

typescript
// src/views/system/position/columns.ts
import { h } from 'vue';
import { NTag } from 'naive-ui';

export const columns = [
  {
    type: 'selection',
    width: 50,
    fixed: 'left',
  },
  {
    title: 'ID',
    key: 'id',
    fixed: 'left',
    width: 50,
  },
  {
    title: '岗位名称',
    key: 'name',
    width: 100,
  },
  {
    title: '岗位状态',
    key: 'status',
    width: 100,
    render(record) {
      return h(
        NTag,
        {
          style: {
            marginRight: '6px',
          },
          bordered: false,
          type: record.status == 1 ? 'success' : 'error',
        },
        {
          default: () => (record.status == 1 ? '正常' : '停用'),
        },
      );
    },
  },
  {
    title: '排序',
    key: 'sort',
    width: 100,
  },
  {
    title: '创建人',
    key: 'createUser',
    width: 100,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
];

querySchemas.ts ​

typescript
// src/views/system/position/querySchemas.ts
import { FormSchema } from '@/components/Form/index';
export const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'NInput',
    label: '岗位名称',
    componentProps: {
      placeholder: '请输入岗位名称',
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      clearable: true,
      options: [
        {
          label: '正常',
          value: '1',
        },
        {
          label: '停用',
          value: '2',
        },
      ],
    },
  },
];

温馨提示

columns.ts 和 querySchemas.ts 独立为配置文件,便于维护和复用。columns 中的 render 函数使用 Vue 的 h() 创建虚拟 DOM,可实现任意复杂的自定义渲染。querySchemas 中的 options 硬编码或通过字典 API 动态获取。NaiveUI 的列配置使用 title/key,组件名使用 NInput/NSelect 等。

总结 ​

页面视图遵循 index.vue + edit.vue + columns.ts + querySchemas.ts 标准模式。列表页使用 BasicForm 搜索 + BasicTable 展示数据 + TableAction 操作按钮,编辑弹窗使用 basicModal + useModal hook 管理弹窗状态。数据流清晰:搜索更新参数 → 刷新表格,操作成功 → emit 事件 → 刷新表格。删除确认使用 NaiveUI 的 useDialog,消息提示使用 useMessage。

小蚂蚁云团队 · 提供技术支持