170行写一个vuex

本文介绍了一个基于Vuex原理的精简版本Vuexx,它简化了原始Vuex的设计并保持核心功能,包括状态管理、响应式更新及模块化支持。通过示例展示了如何使用Vuexx进行状态管理和组件间通信。

Vuex源码不多,1000多行,排除各种报错,兼容,语法糖和拓展功能,其实就干了两件事:
1、把外部传入的store对象组织成了一棵树型的数据结构
2、把state和getters的数据变成响应式,保证界面中可以双向绑定

按照这个需求,结合vuex的实现思路自己写了个vuexx,个人一直不太接受vuex3里的面向对象组织形式,深入源码可以看到state和action、mutation等的组织方式是不太一样的,比如state.module.type 和 dispatch(‘module/type’),太蛋疼了。这块按照个人的理解重新实现了。

App.vue

<template>
  <div>
    vuexx
    <div>root: {{count}}</div>
    <div>rootPlus: {{countPlus}}</div>
    <div>A: {{countA}}</div>
    <div>A: {{countAPlus}}</div>
    <button @click="onClick">add</button>
  </div>
</template>

<script>
import store from './store'

export default {
  name: 'App',

  computed: {
    count () {
      return store.state.count
    },

    countPlus () {
      return store.getters.countPlus
    },

    countA () {
      return store.modules.A.state.count
    },

    countAPlus () {
      return store.modules.A.getters.countPlus
    }
  },

  methods: {
    onClick() {
      store.dispatch('add', 1)
      store.modules.A.dispatch('add', 1)
    }
  }
}
</script>

<style>

</style>

store.js

import Vue from 'vue'
import Vuexx from './lib'

Vue.use(Vuexx)

export default new Vuexx.Store({
  state: {
    count: 1
  },

  getters: {
    countPlus: state => state.count + 1
  },

  mutations: {
    add (state, payload) {
      state.count += payload
    }
  },

  actions: {
    add (context, payload) {
      context.commit('add', payload)
    }
  },

  modules: {
    A: {
      state: {
        count: 10
      },
    
      getters: {
        countPlus: state => state.count + 1
      },
    
      mutations: {
        add (state, payload) {
          state.count += payload
        }
      },
    
      actions: {
        add (context, payload) {
          context.commit('add', payload)
        }
      },    
    }
  }

})

vuexx

let Vue

function install (_Vue) {
  if (Vue && Vue === _Vue) {
    return 
  }

  Vue = _Vue
  applyMixin(Vue)
}

function applyMixin (Vue) {
  const version = Number(Vue.version.split('.')[0])

  if (version >= 2) {
    // 把$store挂载到各个vue实例中,意义不大,此处不实现了
  } else {
    // depracated
  }
}

function isPromise (val) {
  return val && typeof val.then === 'function'
}

function partial (fn, arg) {
  return function () {
    return fn(arg)
  }
}

class Store {
  constructor(options, parent) {
    this.committing = false
    this.state = options.state
    this.getters = options.getters
    this.mutations = options.mutations
    this.actions = options.actions
    this.parent = parent
    
    if (options.modules) {
      this.modules = {}
      Object.keys(options.modules).forEach(moduleName => {
        this.modules[moduleName] = new Store(options.modules[moduleName], this)
      })
    }

    this.installModule()
    this.resetStoreVM()
  }

  installModule() {
    this.registerMutations()
    this.registerActions()
    this.regsiterGetters()
  }

  resetStoreVM () {
    const oldVM = this._vm

    const computed = {}

    if (this.getters) {
      Object.keys(this.getters).forEach(key => {
        computed[key] = partial(this.getters[key], this)
        Object.defineProperty(this.getters, key, {
          get: () => {
            return this._vm[key]
          }
        })
      })
    }

    const silent = Vue.config.silent
    Vue.config.silent = true
    this._vm = new Vue({
      data: {
        $$state: this.state
      },
      computed: computed
    })
    Vue.config.silent = silent

    Object.defineProperty(this, 'state', {
      get: () => {
        return this._vm._data.$$state
      }
    })

    if (oldVM) {
      Vue.nextTick(() => {
        return oldVM.$destroy()
      })
    }
  }

  regsiterGetters () {
    if (this.getters) {
      const originGetters = this.getters
      this.getters = {}

      Object.keys(originGetters).forEach(key => {
        this.getters[key] = () => {
          return originGetters[key](this.state, this.getters)
        }
      })
    }
  }

  registerMutations () {
    if (this.mutations) {
      const orginMutations = this.mutations
      this.mutations = {}
    
      Object.keys(orginMutations).forEach(key => {
        this.mutations[key] = (state, payload) => {
          this.withCommit(() => {
            orginMutations[key].call(this, state, payload)
          })
        }
      })
    }
  }

  registerActions () {
    if (this.actions) {
      const originActions = this.actions
      this.actions = {}
      const context = this

      Object.keys(originActions).forEach(key => {
        this.actions[key] = (payload) => {
          let res = originActions[key].call(this, context, payload)
          if (!isPromise(res)) {
            res = Promise.resolve(res)
          }
          return res
        }
      }) 
    }
  }

  withCommit (fn) {
    const committing = this.committing
    this.committing = true
    fn()
    this.committing = committing
  }

  commit (type, payload) {
    const mutation = this.mutations[type]
    mutation.call(this, this.state, payload)
  }

  dispatch(type, payload) {
    const action = this.actions[type]
    if (action) {
      const res = action.call(this, payload)
      return new Promise((resolve, reject) => {
        res.then(res => {
          resolve(res)
        }, error => {
          reject(error)
        })
      })
    }
  }
}

export default {
  install,
  Store,
}
<c-search-panel ref=“searchPanelRef” :columns=“tableState.columns.concat(extraColumns)” @search=“onSearch”> <template #workzoneSearch=“{ slotScope }”> <a-select showSearch allowClear v-model:value=“slotScope.workzoneNo” :options=“workzoneSearchList” :filter-option=“filterOption” @click=“handleWorkzoneClick”> <c-table :columns=“tableState.columns” :proxy-config=“tableState.proxyConfig” :toolbar=“tableState.toolbar” :rowSelection=“rowSelection” @toolbar-button-click=“onToolbarClick” :sortConfig=“{ showIcon: false }” :pagination=“tableState.pagination” rowKey=“orderNo” ref=“tableRef” > <template #action=“{ record }”> <a-button type=“link” @click=“viewDetail(record)”>查看 <a-button type=“link” @click=“materialApply(record)”> 材料申请 <a-button type=“link” @click=“printDraw(record)”>打印图纸 <template #action=“{ record }”> <a-button type=“link” @click=“viewDraw(record.drawFilePath)”>查看图纸 <a-button type=“link” @click=“pipeLog(record)”>查看日志 <a-button type=“link” @click=“exceptionSubmit(record)”>异常上报 <c-modal v-model:open=“modalVisible” title=“计划派工” @ok=“handleOk” :width=“500” > {{ item.planNo }} <c-modal :title=“‘异常上报’” v-model:open=“exceptionVisible” destroyOnClose okText=“确认” cancelText=“取消” @ok=“submitException” width=“20%” > {{ item.name }} <c-modal v-model:open=“materialApplyVisible” title=“材料申请” @ok=“handleOk” destroyOnClose > <c-build-case-select v-model:value=“materialApplyFormState.orgNo” :fieldNames=“fieldNames” @change=“changeOrg”/> <a-select showSearch allowClear :options=“locationList” :filter-option=“filterOption” v-model:value=“materialApplyFormState.serviceLocationId” @change=“changeLocation” > {{ item.name }} <a-select showSearch allowClear :options=“receiveUserList” :filter-option=“filterOption” v-model:value=“materialApplyFormState.receiverId” @change=“changeReceiver” > {{ item.receiver }} import * as server from “@/packages/piping/api/cppf” import { computed, reactive, ref, onMounted } from “vue” import { validateSearchFields } from “@/utils” import { message } from “ant-design-vue” import dayjs from “dayjs” import { useRouter } from “vue-router” import { useI18n } from “vue-i18n” import { postExceptionManage } from “@/packages/piping/api/exceptionManage” import {getWorkZone, pipeLogPage} from “@/packages/piping/api/basic” import { getDislist } from “@/packages/oem/api/co” import { debounce } from “lodash-es” const { t } = useI18n() const router = useRouter() const tableState = reactive({ toolbar: { buttons: [ { code: “exportExcel”, status: ‘warning’, icon: ‘DownloadOutlined’, name: “导出” }, { code: “planCreateOrder”, status: “primary”, icon: “ScheduleOutlined”, name: “计划派工” }, { code: “printAllReport”, status: “primary”, icon: “PrinterOutlined”, name: “打印” }, // { // code: “printDraws”, // status: “primary”, // icon: “DeploymentUnitOutlined”, // name: “打印图纸” // }, { code: “printCuttingList”, status: “primary”, icon: “PrinterOutlined”, name: “打印下料单” }, { code: “printMaterialList”, status: “primary”, icon: “PrinterOutlined”, name: “打印材料单” }, { code: “printNestingList”, status: “primary”, icon: “PrinterOutlined”, name: “打印套料材料单” }, { code: “printPreTransferOrder”, status: “primary”, icon: “PrinterOutlined”, name: “打印流转卡” }, { code: “materialMoreApply”, status: “primary”, icon: “PrinterOutlined”, name: “材料申请” }, { code: “download”, status: “primary”, icon: “DownloadOutlined”, name: “下载” }, { code: “printRfid”, status: “primary”, icon: “PrinterOutlined”, name: “电子标牌打印”, resource: [{ url: “/service-piping/cp/pipe/pre/work/order/rfidPrintInfo”, method: “POST” }] } ], showFilter: false }, pagination: { pageSize: 20 }, proxyConfig: { autoLoad: false, ajax: { query: async (pagination) => { conditionData = await validateSearchFields(searchPanelRef, conditionData) return server.workOrderPage({ …pagination, …conditionData }) } } }, columns: [ { title: “项目”, dataIndex: “projectNo”, width: 80, type: “project”, options: { options: [], fieldNames: { label: “projId”, value: “projId” } } }, { title: “派工单号”, dataIndex: “orderNo”, width: 120, condition: true, conditionNotice: t(“pipeControll.search.content”) }, { title: “基地”, dataIndex: “orgNo”, type: “buildCase”, width: 80, condition: true }, { title: “派工类型”, dataIndex: “orderType”, type: “select”, width: 100, options: { options: [ {value: ‘普通’, label: “普通”}, {value: ‘船校返回’, label: “船校返回”}, {value: ‘原管修改’, label: “原管修改”}, {value: ‘再现机’, label: “再现机”}, ] }, }, { title: “总长度”, dataIndex: “totalLength”, width: 70 }, { title: “总重量”, dataIndex: “totalWeight”, width: 70 }, { title: “总寸口数”, dataIndex: “totalInch”, width: 80 }, { title: “物量统计”, dataIndex: “pipeCount”, width: 80 }, { title: “下料工位号”, dataIndex: “cutWorkSpaceNo”, width: 80 }, { title: “下料开始日期”, dataIndex: “cutStartDate”, type: “date”, width: 100 }, { title: “下料结束日期”, dataIndex: “cutEndDate”, type: “date”, width: 100 }, { title: “下料状态”, dataIndex: “cutStatus”, width: 80, type: “select”, options: { options: [ { value: “Y”, label: “Y” }, { value: “N”, label: “N” } ] } }, { title: “装配工位号”, dataIndex: “assyWorkSpaceNo”, width: 80 }, { title: “装配工位类型”, dataIndex: “assyWorkSpaceType”, width: 100 }, { title: “装配开始日期”, dataIndex: “assyStartDate”, type: “date”, width: 100 }, { title: “装配结束日期”, dataIndex: “assyEndDate”, type: “date”, width: 100 }, { title: “装配状态”, dataIndex: “assyStatus”, width: 80, type: “select”, options: { options: [ { value: “Y”, label: “Y” }, { value: “N”, label: “N” } ] } }, { title: “焊接工位号”, dataIndex: “weldingWorkSpaceNo”, width: 80 }, { title: “焊接工位类型”, dataIndex: “weldingWorkSpaceType”, width: 100 }, { title: “焊接开始日期”, dataIndex: “weldingStartDate”, type: “date”, width: 100 }, { title: “焊接结束日期”, dataIndex: “weldingEndDate”, type: “date”, width: 100 }, { title: “焊接状态”, dataIndex: “weldingStatus”, width: 80, type: “select”, options: { options: [ { value: “Y”, label: “Y” }, { value: “N”, label: “N” } ] } }, { title: “派工单状态”, dataIndex: “status”, width: 100, type: “select”, formatter: (data) => data.cellValue == -1 ? “作废” : data.cellValue == 0 ? “新建” : data.cellValue == 1 ? “作业中” : data.cellValue == 2 ? “已完成” : “”, options: { options: [ { value: -1, label: “作废” }, { value: 0, label: “新建” }, { value: 1, label: “作业中” }, { value: 2, label: “已完成” } ] } }, { title: “下料领料单号”, dataIndex: “cutMatListNo”, width: 120 }, { title: “装配领料单号”, dataIndex: “assyMatListNo”, width: 120 }, { title: “创建人”, dataIndex: “createUserNo”, type: “employeeDescription”, options: { fieldNames: { label: “createUserName”, value: “createUserNo” } }, width: 110 }, { title: “创建时间”, dataIndex: “createDataDate”, formatter: ({ row }) => { return row.createDate ? dayjs(row.createDate).format(“YYYY-MM-DD”) : “-” }, width: 80, invisible: false, type: “date” }, { title: “操作”, key: “action”, scopedSlots: { customRender: “action” }, width: 240, fixed: “right”, formInvisible: true } ] }) const extraColumns = ref([ { title: “项目”, dataIndex: “projectNo”, width: 80, condition: true, type: “project”, options: { options: [], fieldNames: { label: “projId”, value: “projId” } } }, { title: “作业区”, dataIndex: “workzoneNo”, width: 120, condition: true, type: “select”, formatter: ({row}) => row.workzoneName, scopedSlots: { customSearchRender: “workzoneSearch” }, }, { title: “创建时间”, dataIndex: “createDate”, width: 80, condition: true, type: “date” }, { title: “小票号”, dataIndex: “pipeNoList”, width: 120, condition: true, conditionNotice: t(“pipeControll.search.content”) }, ]) const feedbackPipeData = ref([]) const tableFeedbackPipeState = reactive({ columns: [ { title: “项目”, dataIndex: “projectNo”, width: 50, condition: true, type: “project”, options: { options: [], fieldNames: { label: “projId”, value: “projId” } } }, { title: “图号”, dataIndex: “drawNo”, width: 170 }, { title: “作业对象”, dataIndex: “block”, width: 70 }, { title: “小票号”, dataIndex: “pipeNo”, width: 150 }, { title: “版本号”, dataIndex: “pipeVersion”, width: 60 }, { title: “最新版”, dataIndex: “isTopVersion”, width: 60, type: “select”, options: { options: [ { label: “Y”, value: “Y” }, { label: “N”, value: “N” } ] } }, { title: “是否删除”, dataIndex: “isDelete”, width: 80, type: “select”, options: { options: [ { label: “Y”, value: “Y” }, { label: “N”, value: “N” } ] } }, { title: “是否暂停”, dataIndex: “isPause”, width: 80, type: “select”, options: { options: [ { label: “Y”, value: “Y” }, { label: “N”, value: “N” } ] } }, { title: “下料定额工时”, dataIndex: “cutQuotaWorkhour”, width: 100 }, { title: “装配定额工时”, dataIndex: “assyQuotaWorkhour”, width: 100 }, { title: “焊接定额工时”, dataIndex: “weldingQuotaWorkhour”, width: 100 }, { title: “下料完成时间”, dataIndex: “realCutFinishDate”, type: “date”, width: 100 }, { title: “装配完成时间”, dataIndex: “realAssyFinishDate”, type: “date”, width: 100 }, { title: “焊接完成时间”, dataIndex: “realWeldingFinishDate”, type: “date”, width: 100 }, { title: “操作”, key: “action”, scopedSlots: { customRender: “action” }, width: 240, fixed: “right”, formInvisible: true } ] }) const workzoneSearchList = ref([]) const tableRef = ref(null) const formRef = ref() const searchPanelRef = ref(null) const searchForm = computed(() => { if (searchPanelRef.value) { return searchPanelRef.value.getForm() } return null }) const modalRef = ref(null) const ctable = computed(() => tableRef.value?.getTable()) let conditionData = {} const open = ref(false) const modalVisible = ref(false) const planList = ref([]) const formState = reactive({ planNoList: [], selectedDateRange: [] }) const today = dayjs().startOf(“day”) const disabledDate = (current) => { return current && current < today } const fieldNames = ref({ value: ‘orgNo’, label: ‘name’ }) const materialApplyVisible = ref(false) const rules = { planNoList: [{ required: true, message: “请选择预制计划” }], selectedDateRange: [{ required: true, message: “请选择日期” }] } const materialApplyRules = { orgNo: [{ required: true, message: “请选择基地” }], serviceLocationId: [{ required: true, message: “请选择送达位置” }], receiverId: [{ required: true, message: “请选择接收人” }], } const materialApplyFormRef = ref() const materialApplyFormState = reactive({ orgNo: “”, serviceLocationId: “”, receiverId: “”, receiverTel: “” }) const locationList = ref([]) const receiveUserList = ref([]) const rowSelection = computed(() => { return { type: “checkbox”, // 确保是多选模式 selectedRowKeys: tableState.selectedRowKeys, onChange: (selectedRowKeys, selectedRows, event) => { tableState.selectedRowKeys = selectedRowKeys tableState.selectedRows = selectedRows // 保存选中的数据 console.log(“onChange”, selectedRowKeys, selectedRows, event) }, onSelect: (record, selected, selectedRows, nativeEvent) => { tableState.selectedRows = selectedRows // 更新选中的数据 console.log(“onSelect”, record, selected, selectedRows, nativeEvent) }, onSelectAll: (selected, selectedRows, changeRows) => { tableState.selectedRows = selectedRows // 更新选中的数据 console.log(“onSelectAll”, selected, selectedRows, changeRows) } } }) const conditionLogData = ref() const logVisible = ref(false) const tableLogState = reactive({ toolbar: {}, selectedRowKeys: [], pagination: { pageSize: 20, pageSizeOptions: [20, 100, 400] }, proxyConfig: { autoLoad: true, ajax: { query: (pagination) => pipeLogPage({ …pagination, …conditionLogData.value }) } }, columns: [ { title: “操作时间”, dataIndex: “createDate”, type: “datetime” }, { title: “操作人”, dataIndex: “createUserNo”, type: “employeeDescription”, align: “center”, options: { fieldNames: { label: “createUserName”, value: “createUserNo” } }, width: 100 }, { title: “操作类型”, dataIndex: “event” }, { title: “操作详情”, dataIndex: “msg” } ] }) const localStorage = window.localStorage const projectNo = ref(“”) const pipeNo = ref(“”) const pipeVersion = ref(null) const orgNo = ref(“”) const exceptionVisible = ref(false) const exceptionTypeList = ref([]) const exceptionFormRef = ref() const exceptionFormState = ref({ exceptionType: “”, exceptionMsg: “” }) const isSubmitting = ref(false) const onToolbarClick = (target) => { switch (target.code) { case “exportExcel”: funExportModal() break case “planCreateOrder”: planCreateOrder() break case “printMaterialList”: printMaterialList() break case “printCuttingList”: printCuttingList() break case “printNestingList”: printNestingList() break case “printPreTransferOrder”: printPreTransferOrder() break case “printAllReport”: printAllReport() break case “download”: download() break case “printRfid”: printRfid() break // case “printDraws”: // download() // breakprintDraws default: break } } const changeOrg = (orgNo) => { materialApplyFormState.serviceLocationId = “” materialApplyFormState.receiverId = “” materialApplyFormState.receiverTel = “” server.getLocationDropList({ orgNo: orgNo }).then(res => { locationList.value = res.data; }); } const changeLocation = (locationId) => { server.getLocationDropList({ id: locationId, }).then(res => { receiveUserList.value = res.data[0].receiverList; if (receiveUserList.value && receiveUserList.value.length > 0) { materialApplyFormState.receiverId = receiveUserList.value[0].id; materialApplyFormState.receiverTel = receiveUserList.value[0].receiverTel; } }) } const changeReceiver = (receiverId) => { const matchedUser = receiveUserList.value.find(user => user.id == receiverId); if (matchedUser) { materialApplyFormState.receiverTel = matchedUser.receiverTel; } } const handleWorkzoneClick = () => { workzoneSearchList.value = [] const searchFormValues = searchForm.value?.getFieldsValue() if (!searchFormValues.orgNo) { return } getWorkZone({majors: “管路”, orgNo: searchFormValues.orgNo}).then((res) => { workzoneSearchList.value = res.data.map(item => { return { label: item.name, value: item.code } }) }) } // 打印材料单函数 const printMaterialList = async () => { try { // 验证选择 if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } // 获取派工单号 const orderNos = tableState.selectedRows .map(row => row.orderNo) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } router.push({ path: “/piping/cppf/preAssyOrder”, query: { orderNos: orderNos.join(“,”) } }) } catch (error) { console.error(“打印材料单失败:”, error) message.error(“打印失败,请重试”) } } // 打印下料单函数 const printCuttingList = async () => { try { // 验证选择 if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } // 获取派工单号 const orderNos = tableState.selectedRows .map(row => row.orderNo) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } router.push({ path: “/piping/cppf/preCutOrder”, query: { orderNos: orderNos.join(“,”) } }) } catch (error) { console.error(“打印下料单失败:”, error) message.error(“打印失败,请重试”) } } // 打印套料材料单 const printNestingList = async () => { try { // 验证选择 if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } // 获取派工单号 const orderNos = tableState.selectedRows .map(row => row.orderNo) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } router.push({ path: “/piping/cppf/preNestingOrder”, query: { orderNos: orderNos.join(“,”) } }) } catch (error) { console.error(“打印套料材料单失败:”, error) message.error(“打印失败,请重试”) } } // 打印 const printAllReport = async () => { try { // 验证选择 if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } // 获取派工单号 const orderNos = tableState.selectedRows .map(row => row.orderNo) // 获取项目编号 const projetNos = tableState.selectedRows.map(row => row.projectNo) const totalLengths = tableState.selectedRows.map(row => row.totalLength) const totalWeights = tableState.selectedRows.map(row => row.totalWeight) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } router.push({ path: “/piping/cppf/cpPipeAllReport”, query: { orderNos: orderNos.join(“,”), projetNos: projetNos.join(“,”), totalLengths: totalLengths.join(“,”), totalWeights: totalWeights.join(“,”) } }) } catch (error) { message.error(“打印失败,请重试”) } } // 打印 // const printDraws = async () => { // try { // if (!tableState.selectedRows?.length) { // message.warning(“请至少选择一条数据”) // return // } // const orderNos = tableState.selectedRows // .map(row => row.orderNo) // .filter(Boolean) // 过滤空值 // if (!orderNos.length) { // message.warning(“未找到有效的派工单号”) // return // } // const token = localStorage.getItem(“token”) // const searchParams = new URLSearchParams() // searchParams.append(‘orderNos’, orderNos) // searchParams.append(‘token’, token) // const baseUrl = “http://epc/api/service-piping/cp/pipe/pre/work/order/printDraws” // const fullUrl = ${baseUrl}?${searchParams.toString()} // window.open(fullUrl) // } catch (error) { // console.error(‘打印失败:’, error) // message.error(“打印失败,请重试”) // } // } const printRfid = async () => { try { // 验证选择 if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } // 获取派工单号 const orderNos = tableState.selectedRows .map(row => row.orderNo) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } router.push({ path: “/piping/cppf/cpPipePrint”, query: { orderNos: orderNos.join(“,”) } }) } catch (error) { message.error(“打印失败,请重试”) } } // 下载 const download = async () => { try { if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } const orderNos = tableState.selectedRows .map(row => row.orderNo) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } await server.downloadworkOrder(orderNos); } catch (error) { console.error(“下载失败:”, error) message.error(“下载失败,请重试”) } } onMounted(() => { getDislist({ code: “CP_EXCEPTION_TYPE” }).then((res) => { exceptionTypeList.value = res.data }) }) //搜索 const onSearch = () => { ctable.value.commitProxy(“reload”) } const viewDetail = (record) => { open.value = true orgNo.value = record.orgNo server.workOrderPipeDetail({ orderNo: record.orderNo, projectNo: record.projectNo }).then((res) => { feedbackPipeData.value = res.data }) } // const cutOrder = (record) => { // router.push({ // path: “/piping/cppf/preCutOrder”, // query: { // orderNo: record.orderNo // } // }) // } // const materialOrder = (record) => { // router.push({ // path: “/piping/cppf/preAssyOrder”, // query: { // orderNo: record.orderNo // } // }) // } // const nestingMaterialOrder = (record) => { // router.push({ // path: “/piping/cppf/preNestingOrder”, // query: { // orderNo: record.orderNo // } // }) // } const materialApply = (record) => { formRef.value.validate().then(() => { locationList.value.forEach(item => { if (item.id == materialApplyFormState.serviceLocationId) { record.serviceLocationName = item.name; } }); receiveUserList.value.forEach(item => { if (item.id == materialApplyFormState.receiverId) { record.receiverCode = item.receiverId; } }); const applyData = { orderNo: record.orderNo, orgNo: materialApplyFormState.orgNo, locationOrgName: “”, receiverCode: record.receiverCode, receiverId: materialApplyFormState.receiverId, receiverTel: materialApplyFormState.receiverTel, serviceLocationId: materialApplyFormState.serviceLocationId, serviceLocationName: record.serviceLocationName, }; server.orderMaterialReq(applyData).then(() => { message.success(“申请成功”) }) }) } const printPreTransferOrder = () => { try { if (!tableState.selectedRows?.length) { message.warning(“请至少选择一条数据”) return } const orderNos = tableState.selectedRows .map(row => row.orderNo) .filter(Boolean) if (orderNos.length === 0) { message.warning(“未找到有效的派工单号”) return } router.push({ path: “/piping/cppf/preTransferOrder”, query: { orderNos: orderNos.join(“,”) } }) } catch (error) { console.error(“打印失败:”, error) message.error(“打印失败,请重试”) } } // const electronicTag = (record) => { // router.push({ // path: “/piping/cppf/cpPipePrint”, // query: { // orderNos: record.orderNo // } // }) // } const viewDraw = (drawFilePath) => { const encodedFilePath = encodeURIComponent(drawFilePath) const token = localStorage.getItem(“token”) window.open( http://epc/api/service-piping/cp/pipe/design/info/getPcPipeDraw?drawFilePath=${encodedFilePath}&token=${token} ); } const printDraw = (record) => { window.open( “http://epc/api/service-piping/cp/pipe/pre/work/order/printDraw?orderNo=” + record.orderNo + “&token=” + localStorage.getItem(“token”) ) } const planCreateOrder = () => { modalVisible.value = true formState.planNoList = [] formState.selectedDateRange = [] server.getPipePlanDropList({ isTopVersion: “Y”, planType: “预制” }).then(res => { planList.value = res.data || [] }) } const handleOk = debounce(() => { if (isSubmitting.value) return formRef.value.validate().then(() => { isSubmitting.value = true const planIdList = planList.value .filter(p => formState.planNoList.includes(p.planNo)) .map(p => p.id) const [startDate, endDate] = formState.selectedDateRange const params = { planIdList, startDate, endDate } server.createPreOrder(params) .then(() => { message.success(“派工成功”) modalVisible.value = false ctable.value.commitProxy(“reload”) }) .catch((error) => { console.error(“派工失败:”, error) message.error(“派工失败,请重试”) }) .finally(() => { isSubmitting.value = false }) }).catch((error) => { console.error(“表单验证失败:”, error) message.error(“请检查表单填是否正确”) isSubmitting.value = false }) }, 300) const exceptionSubmit = (record) => { exceptionFormState.value = { exceptionType: “”, exceptionMsg: “” } projectNo.value = record.projectNo pipeNo.value = record.pipeNo pipeVersion.value = record.pipeVersion exceptionVisible.value = true } const submitException = () => { exceptionFormRef.value .validate().then(() => { const submitData = [{ projectNo: projectNo.value, bomNo: pipeNo.value, bomVersion: pipeVersion.value, orgNo: orgNo.value, exceptionType: exceptionFormState.value.exceptionType, exceptionMsg: exceptionFormState.value.exceptionMsg }] postExceptionManage(submitData).then(() => { message.success(“上报成功”) exceptionVisible.value = false }) }) } const pipeLog = (record) => { logVisible.value = true const logCondition = { projectNo: record.projectNo, pipeNo: record.pipeNo, pipeVersion: record.pipeVersion } conditionLogData.value = logCondition } const funExportModal = () => { searchForm.value.validateFields().then((values) => { server.preOrderExportExcel({…values}) }) } const filterOption = (input, option) => { return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0 } 其中const applyData = { orderNo: record.orderNo, orgNo: materialApplyFormState.orgNo, locationOrgName: “”, receiverCode: record.receiverCode, receiverId: materialApplyFormState.receiverId, receiverTel: materialApplyFormState.receiverTel, serviceLocationId: materialApplyFormState.serviceLocationId, serviceLocationName: record.serviceLocationName, };的locationOrgName要取值const fieldNames = ref({ value: ‘orgNo’, label: ‘name’ })里的label的值 <a-form-item label="基地" name="orgNo"> <c-build-case-select v-model:value="materialApplyFormState.orgNo" :fieldNames="fieldNames" @change="changeOrg"/> </a-form-item>
11-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值