在vue页面中添加组件到底有多方便

news2024/11/26 22:49:37

修改vue写的前端页面到底有多方便?如果熟练的话,出乎你想象的快。

原来的页面:/admin/stock

原来的文件地址:src\views\admin\stock\Stock.vue

另一个页面有个入库功能,需要转移到上面的页面中:

路径:/purchase/request

地址:src\views\purchase\request\Request.vue

入库功能包括一个开启按键(1)和一个弹出表单(2):

 

开启按键代码:

<a-button type="primary" ghost @click="warehouse">入库</a-button>
    warehouse () {
      this.stockAdd.visiable = true
    },

弹出表单窗口是一个独立存在的vue文件:

路径:src\views\purchase\request\RequestAdd.vue

RequestAdd.vue代码:

<template>
  <a-drawer
    title="物品入库"
    :maskClosable="false"
    placement="right"
    :closable="false"
    :visible="show"
    :width="1200"
    @close="onClose"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;"
  >
    <a-form :form="form" layout="horizontal">
      <a-row :gutter="50">
        <a-col :span="12">
          <a-form-item label='保管人' v-bind="formItemLayout">
            <a-input v-decorator="[
            'custodian',
            { rules: [{ required: true, message: '请输入保管人!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label='入库人' v-bind="formItemLayout">
            <a-input v-decorator="[
            'putUser',
            { rules: [{ required: true, message: '请输入入库人!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label='备注消息' v-bind="formItemLayout">
            <a-textarea :rows="4" v-decorator="[
            'content',
             { rules: [{ required: true, message: '请输入名称!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-table :columns="columns" :data-source="dataList">
            <template slot="nameShow" slot-scope="text, record">
              <a-input v-model="record.name"></a-input>
            </template>
            <template slot="typeShow" slot-scope="text, record">
              <a-input v-model="record.type"></a-input>
            </template>
            <template slot="typeIdShow" slot-scope="text, record">
              <a-select v-model="record.typeId" style="width: 100%">
                <a-select-option v-for="(item, index) in consumableType" :value="item.id" :key="index">{{ item.name }}</a-select-option>
              </a-select>
            </template>
            <template slot="unitShow" slot-scope="text, record">
              <a-input v-model="record.unit"></a-input>
            </template>
            <template slot="amountShow" slot-scope="text, record">
              <a-input-number v-model="record.amount" :min="1" :step="1"/>
            </template>
            <template slot="priceShow" slot-scope="text, record">
              <a-input-number v-model="record.price" :min="1"/>
            </template>
          </a-table>
          <a-button @click="dataAdd" type="primary" ghost size="large" style="margin-top: 10px;width: 100%">
            新增物品
          </a-button>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑?" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {mapState} from 'vuex'
const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 }
}
export default {
  name: 'requestAdd',
  props: {
    requestAddVisiable: {
      default: false
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    show: {
      get: function () {
        return this.requestAddVisiable
      },
      set: function () {
      }
    },
    columns () {
      return [{
        title: '物品名称',
        dataIndex: 'name',
        scopedSlots: {customRender: 'nameShow'}
      }, {
        title: '型号',
        dataIndex: 'type',
        scopedSlots: {customRender: 'typeShow'}
      }, {
        title: '数量',
        dataIndex: 'amount',
        scopedSlots: {customRender: 'amountShow'}
      }, {
        title: '所属类型',
        dataIndex: 'typeId',
        width: 200,
        scopedSlots: {customRender: 'typeIdShow'}
      }, {
        title: '单位',
        dataIndex: 'unit',
        scopedSlots: {customRender: 'unitShow'}
      }, {
        title: '单价',
        dataIndex: 'price',
        scopedSlots: {customRender: 'priceShow'}
      }]
    }
  },
  mounted () {
    this.getConsumableType()
  },
  data () {
    return {
      dataList: [],
      formItemLayout,
      form: this.$form.createForm(this),
      loading: false,
      consumableType: []
    }
  },
  methods: {
    getConsumableType () {
      this.$get('/cos/consumable-type/list').then((r) => {
        this.consumableType = r.data.data
      })
    },
    dataAdd () {
      this.dataList.push({name: '', type: '', typeId: '', unit: '', amount: '', price: ''})
    },
    reset () {
      this.loading = false
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      let price = 0
      this.dataList.forEach(item => {
        price += item.price * item.amount
      })
      this.form.validateFields((err, values) => {
        values.price = price
        values.goods = JSON.stringify(this.dataList)
        if (!err) {
          this.loading = true
          this.$post('/cos/stock-info/put', {
            ...values
          }).then((r) => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>

在Request.vue中引用RequestAdd.vue的方法:

    <request-add
      v-if="requestAdd.visiable"
      @close="handleRequestAddClose"
      @success="handleRequestAddSuccess"
      :requestAddVisiable="requestAdd.visiable">
    </request-add>
<script>
...
import RequestAdd from './RequestAdd'
...

export default {
  ...
  data () {
    return {
      ...
      requestAdd: {
        visiable: false
      },
      ...
    }
  },
  ...
  methods: {
    ...
    handleRequestAddClose () {
      this.requestAdd.visiable = false
    },
    handleRequestAddSuccess () {
      this.requestAdd.visiable = false
      this.$message.success('入库成功')
      this.search()
    },
    ...
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    ...
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空,则设置表格当前第几页,每页条数,并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.size = this.paginationInfo.pageSize
        params.current = this.paginationInfo.current
      } else {
        // 如果分页信息为空,则设置为默认值
        params.size = this.pagination.defaultPageSize
        params.current = this.pagination.defaultCurrent
      }
      if (params.typeId === undefined) {
        delete params.typeId
      }
      this.$get('/cos/stock-info/page', {
        ...params
      }).then((r) => {
        let data = r.data.data
        const pagination = {...this.pagination}
        pagination.total = data.total
        this.dataSource = data.records
        this.pagination = pagination
        // 数据加载完毕,关闭loading
        this.loading = false
      })
    }
  },
  watch: {}
}
</script>

实际上就是在Request.vue中添加一个数据对象(requestAdd.visiable)和两个方法(handleRequestAddClose、handleRequestAddSuccess)

开始改造

将RequestAdd.vue文件加入Stock.vue所在路径,修改合适的文件名称为StockAdd.vue,同时修改StockAdd.vue对外暴露的name和props的名称。

在Stock.vue的<template>代码适当位置添加按键和表单(7行代码):

 在Stock.vue的<script>代码中添加相关的引用(2行代码)、数据(3行代码)、函数(8行代码):

 

总结

改造过程,共复制vue文件1个,修改代码23行。熟悉代码的情况下,修改用时很短。

说明vue组件化特性为代码复用带来极大便利。

源码

src\views\purchase\request\Request.vue

<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row :gutter="15">
          <div :class="advanced ? null: 'fold'">
            <a-col :md="6" :sm="24">
              <a-form-item
                label="物品名称"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-input v-model="queryParams.name"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item
                label="物品型号"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-input v-model="queryParams.type"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item
                label="物品类型"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-select v-model="queryParams.typeId" style="width: 100%" allowClear>
                  <a-select-option v-for="(item, index) in consumableType" :value="item.id" :key="index">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </span>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="add">入库</a-button>
        <!-- <a-button @click="batchDelete">删除</a-button> 后台API不存在/cos/request-type/{id}删除接口 这个按键是多余的 -->
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="titleShow" slot-scope="text, record">
          <template>
            <a-badge status="processing"/>
            <a-tooltip>
              <template slot="title">
                {{ record.title }}
              </template>
              {{ record.title.slice(0, 8) }} ...
            </a-tooltip>
          </template>
        </template>
        <template slot="contentShow" slot-scope="text, record">
          <template>
            <a-tooltip>
              <template slot="title">
                {{ record.content }}
              </template>
              {{ record.content.slice(0, 30) }} ...
            </a-tooltip>
          </template>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修 改"></a-icon>
        </template>
      </a-table>
    </div>
    <request-add
      v-if="requestAdd.visiable"
      @close="handleRequestAddClose"
      @success="handleRequestAddSuccess"
      :requestAddVisiable="requestAdd.visiable">
    </request-add>
  </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import RequestAdd from './RequestAdd'
import {mapState} from 'vuex'
import moment from 'moment'
moment.locale('zh-cn')

export default {
  name: 'request',
  components: {RequestAdd, RangeDate},
  data () {
    return {
      advanced: false,
      requestAdd: {
        visiable: false
      },
      requestEdit: {
        visiable: false
      },
      queryParams: {},
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录,共 ${total} 条记录`
      },
      consumableType: []
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    columns () {
      return [{
        title: '物品名称',
        dataIndex: 'name'
      }, {
        title: '型号',
        dataIndex: 'type',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '物品数量',
        dataIndex: 'amount',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '单位',
        dataIndex: 'unit',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '单价',
        dataIndex: 'price',
        customRender: (text, row, index) => {
          if (text !== null) {
            return '¥' + text.toFixed(2)
          } else {
            return '- -'
          }
        }
      }, {
        title: '总价',
        dataIndex: 'allPrice',
        customRender: (text, row, index) => {
          return '¥' + (row.price * row.amount).toFixed(2)
        }
      }, {
        title: '物品类型',
        dataIndex: 'consumableType',
        customRender: (text, row, index) => {
          if (text !== null) {
            return <a-tag>{text}</a-tag>
          } else {
            return '- -'
          }
        }
      }, {
        title: '备注',
        dataIndex: 'content',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '入库时间',
        dataIndex: 'createDate',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }]
    }
  },
  mounted () {
    this.fetch()
    this.getConsumableType()
  },
  methods: {
    getConsumableType () {
      this.$get('/cos/consumable-type/list').then((r) => {
        this.consumableType = r.data.data
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    add () {
      this.requestAdd.visiable = true
    },
    handleRequestAddClose () {
      this.requestAdd.visiable = false
    },
    handleRequestAddSuccess () {
      this.requestAdd.visiable = false
      this.$message.success('入库成功')
      this.search()
    },
    handleDeptChange (value) {
      this.queryParams.deptId = value || ''
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后,这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let ids = that.selectedRowKeys.join(',')
          that.$delete('/cos/request-type/' + ids).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data,用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空,则设置表格当前第几页,每页条数,并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.size = this.paginationInfo.pageSize
        params.current = this.paginationInfo.current
      } else {
        // 如果分页信息为空,则设置为默认值
        params.size = this.pagination.defaultPageSize
        params.current = this.pagination.defaultCurrent
      }
      if (params.typeId === undefined) {
        delete params.typeId
      }
      this.$get('/cos/stock-info/page', {
        ...params
      }).then((r) => {
        let data = r.data.data
        const pagination = {...this.pagination}
        pagination.total = data.total
        this.dataSource = data.records
        this.pagination = pagination
        // 数据加载完毕,关闭loading
        this.loading = false
      })
    }
  },
  watch: {}
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>

src\views\purchase\request\RequestAdd.vue:

<template>
  <a-drawer
    title="物品入库"
    :maskClosable="false"
    placement="right"
    :closable="false"
    :visible="show"
    :width="1200"
    @close="onClose"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;"
  >
    <a-form :form="form" layout="horizontal">
      <a-row :gutter="50">
        <a-col :span="12">
          <a-form-item label='保管人' v-bind="formItemLayout">
            <a-input v-decorator="[
            'custodian',
            { rules: [{ required: true, message: '请输入保管人!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label='入库人' v-bind="formItemLayout">
            <a-input v-decorator="[
            'putUser',
            { rules: [{ required: true, message: '请输入入库人!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label='备注消息' v-bind="formItemLayout">
            <a-textarea :rows="4" v-decorator="[
            'content',
             { rules: [{ required: true, message: '请输入名称!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-table :columns="columns" :data-source="dataList">
            <template slot="nameShow" slot-scope="text, record">
              <a-input v-model="record.name"></a-input>
            </template>
            <template slot="typeShow" slot-scope="text, record">
              <a-input v-model="record.type"></a-input>
            </template>
            <template slot="typeIdShow" slot-scope="text, record">
              <a-select v-model="record.typeId" style="width: 100%">
                <a-select-option v-for="(item, index) in consumableType" :value="item.id" :key="index">{{ item.name }}</a-select-option>
              </a-select>
            </template>
            <template slot="unitShow" slot-scope="text, record">
              <a-input v-model="record.unit"></a-input>
            </template>
            <template slot="amountShow" slot-scope="text, record">
              <a-input-number v-model="record.amount" :min="1" :step="1"/>
            </template>
            <template slot="priceShow" slot-scope="text, record">
              <a-input-number v-model="record.price" :min="1"/>
            </template>
          </a-table>
          <a-button @click="dataAdd" type="primary" ghost size="large" style="margin-top: 10px;width: 100%">
            新增物品
          </a-button>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑?" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {mapState} from 'vuex'
const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 }
}
export default {
  name: 'requestAdd',
  props: {
    requestAddVisiable: {
      default: false
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    show: {
      get: function () {
        return this.requestAddVisiable
      },
      set: function () {
      }
    },
    columns () {
      return [{
        title: '物品名称',
        dataIndex: 'name',
        scopedSlots: {customRender: 'nameShow'}
      }, {
        title: '型号',
        dataIndex: 'type',
        scopedSlots: {customRender: 'typeShow'}
      }, {
        title: '数量',
        dataIndex: 'amount',
        scopedSlots: {customRender: 'amountShow'}
      }, {
        title: '所属类型',
        dataIndex: 'typeId',
        width: 200,
        scopedSlots: {customRender: 'typeIdShow'}
      }, {
        title: '单位',
        dataIndex: 'unit',
        scopedSlots: {customRender: 'unitShow'}
      }, {
        title: '单价',
        dataIndex: 'price',
        scopedSlots: {customRender: 'priceShow'}
      }]
    }
  },
  mounted () {
    this.getConsumableType()
  },
  data () {
    return {
      dataList: [],
      formItemLayout,
      form: this.$form.createForm(this),
      loading: false,
      consumableType: []
    }
  },
  methods: {
    getConsumableType () {
      this.$get('/cos/consumable-type/list').then((r) => {
        this.consumableType = r.data.data
      })
    },
    dataAdd () {
      this.dataList.push({name: '', type: '', typeId: '', unit: '', amount: '', price: ''})
    },
    reset () {
      this.loading = false
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      let price = 0
      this.dataList.forEach(item => {
        price += item.price * item.amount
      })
      this.form.validateFields((err, values) => {
        values.price = price
        values.goods = JSON.stringify(this.dataList)
        if (!err) {
          this.loading = true
          this.$post('/cos/stock-info/put', {
            ...values
          }).then((r) => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>

 src\views\admin\stock\Stock.vue(修改后):

<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row :gutter="15">
          <div :class="advanced ? null: 'fold'">
            <a-col :md="6" :sm="24">
              <a-form-item
                label="物品名称"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-input v-model="queryParams.name"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item
                label="物品型号"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-input v-model="queryParams.type"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item
                label="物品类型"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-select v-model="queryParams.typeId" style="width: 100%" allowClear>
                  <a-select-option v-for="(item, index) in consumableType" :value="item.id" :key="index">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </span>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="warehouse">入库</a-button>
        <a-button type="primary" ghost @click="outOfWarehouse">出库</a-button>
        <!--<a-button @click="batchDelete">删除</a-button>-->
      </div>
      <!-- 表格区域  -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="titleShow" slot-scope="text, record">
          <template>
            <a-badge status="processing"/>
            <a-tooltip>
              <template slot="title">
                {{ record.title }}
              </template>
              {{ record.title.slice(0, 8) }} ...
            </a-tooltip>
          </template>
        </template>
        <template slot="contentShow" slot-scope="text, record">
          <template>
            <a-tooltip>
              <template slot="title">
                {{ record.content }}
              </template>
              {{ record.content.slice(0, 30) }} ...
            </a-tooltip>
          </template>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修 改"></a-icon>
        </template>
      </a-table>
    </div>
    <stock-add
      v-if="stockAdd.visiable"
      @close="handleStockAddClose"
      @success="handleStockAddSuccess"
      :stockAddVisiable="stockAdd.visiable">
    </stock-add>
    <stock-out
      @close="handleStockoutClose"
      @success="handleStockoutSuccess"
      :stockoutData="stockout.data"
      :stockoutVisiable="stockout.visiable">
    </stock-out>
  </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import {mapState} from 'vuex'
import StockOut from './StockOut'
import StockAdd from './StockAdd'
import moment from 'moment'
moment.locale('zh-cn')

export default {
  name: 'Stock',
  components: {StockOut, StockAdd, RangeDate},
  data () {
    return {
      advanced: false,
      stockAdd: {
        visiable: false
      },
      stockout: {
        visiable: false,
        data: null
      },
      requestEdit: {
        visiable: false
      },
      queryParams: {},
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录,共 ${total} 条记录`
      },
      consumableType: []
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    columns () {
      return [{
        title: '物品名称',
        dataIndex: 'name'
      }, {
        title: '型号',
        dataIndex: 'type',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '物品数量',
        dataIndex: 'amount',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '单位',
        dataIndex: 'unit',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '单价',
        dataIndex: 'price',
        customRender: (text, row, index) => {
          if (text !== null) {
            return '¥' + text.toFixed(2)
          } else {
            return '- -'
          }
        }
      }, {
        title: '总价',
        dataIndex: 'allPrice',
        customRender: (text, row, index) => {
          return '¥' + (row.price * row.amount).toFixed(2)
        }
      }, {
        title: '物品类型',
        dataIndex: 'consumableType',
        customRender: (text, row, index) => {
          if (text !== null) {
            return <a-tag>{text}</a-tag>
          } else {
            return '- -'
          }
        }
      }, {
        title: '备注',
        dataIndex: 'content',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }, {
        title: '入库时间',
        dataIndex: 'createDate',
        customRender: (text, row, index) => {
          if (text !== null) {
            return text
          } else {
            return '- -'
          }
        }
      }]
    }
  },
  mounted () {
    this.fetch()
    this.getConsumableType()
  },
  methods: {
    getConsumableType () {
      this.$get('/cos/consumable-type/list').then((r) => {
        this.consumableType = r.data.data
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      selectedRows.forEach(item => {
        if (item.amount === 0) {
          this.$message.warning(`${item.name}没有库存!`)
          return false
        }
      })
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // “入库”按键响应
    warehouse () {
      this.stockAdd.visiable = true
    },
    // “出库”按键的响应方法
    outOfWarehouse () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要出库的物品')
        return
      }
      let goods = this.selectedRows
      let amt = false
      let warningwords = '某个物品'
      goods.forEach(item => {
        item.max = item.amount
        if (item.amount === 0) {
          amt = true
          warningwords = item.name
        }
      })
      if (amt) {
        this.$message.warning(`${warningwords}没有库存!`)
        return
      }
      this.stockout.data = JSON.parse(JSON.stringify(goods))
      this.stockout.visiable = true
    },
    handleStockAddClose () {
      this.stockAdd.visiable = false
    },
    handleStockAddSuccess () {
      this.stockAdd.visiable = false
      this.$message.success('入库成功')
      this.search()
    },
    handleStockoutClose () {
      this.stockout.visiable = false
    },
    handleStockoutSuccess () {
      this.stockout.visiable = false
      this.selectedRows = []
      this.selectedRowKeys = []
      this.$message.success('出库成功')
      this.search()
    },
    handleDeptChange (value) {
      this.queryParams.deptId = value || ''
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后,这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let ids = that.selectedRowKeys.join(',')
          that.$delete('/cos/request-type/' + ids).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.selectedRows = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
          that.selectedRows = []
        }
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data,用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空,则设置表格当前第几页,每页条数,并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.size = this.paginationInfo.pageSize
        params.current = this.paginationInfo.current
      } else {
        // 如果分页信息为空,则设置为默认值
        params.size = this.pagination.defaultPageSize
        params.current = this.pagination.defaultCurrent
      }
      if (params.typeId === undefined) {
        delete params.typeId
      }
      this.$get('/cos/stock-info/page', {
        ...params
      }).then((r) => {
        let data = r.data.data
        const pagination = {...this.pagination}
        pagination.total = data.total
        this.dataSource = data.records
        this.pagination = pagination
        // 数据加载完毕,关闭loading
        this.loading = false
      })
    }
  },
  watch: {}
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>

src\views\admin\stock\StockAdd.vue(修改后):

<template>
  <a-drawer
    title="物品入库"
    :maskClosable="false"
    placement="right"
    :closable="false"
    :visible="show"
    :width="1200"
    @close="onClose"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;"
  >
    <a-form :form="form" layout="horizontal">
      <a-row :gutter="50">
        <a-col :span="12">
          <a-form-item label='保管人' v-bind="formItemLayout">
            <a-input v-decorator="[
            'custodian',
            { rules: [{ required: true, message: '请输入保管人!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label='入库人' v-bind="formItemLayout">
            <a-input v-decorator="[
            'putUser',
            { rules: [{ required: true, message: '请输入入库人!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label='备注消息' v-bind="formItemLayout">
            <a-textarea :rows="4" v-decorator="[
            'content',
             { rules: [{ required: true, message: '请输入名称!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-table :columns="columns" :data-source="dataList">
            <template slot="nameShow" slot-scope="text, record">
              <a-input v-model="record.name"></a-input>
            </template>
            <template slot="typeShow" slot-scope="text, record">
              <a-input v-model="record.type"></a-input>
            </template>
            <template slot="typeIdShow" slot-scope="text, record">
              <a-select v-model="record.typeId" style="width: 100%">
                <a-select-option v-for="(item, index) in consumableType" :value="item.id" :key="index">{{ item.name }}</a-select-option>
              </a-select>
            </template>
            <template slot="unitShow" slot-scope="text, record">
              <a-input v-model="record.unit"></a-input>
            </template>
            <template slot="amountShow" slot-scope="text, record">
              <a-input-number v-model="record.amount" :min="1" :step="1"/>
            </template>
            <template slot="priceShow" slot-scope="text, record">
              <a-input-number v-model="record.price" :min="1"/>
            </template>
          </a-table>
          <a-button @click="dataAdd" type="primary" ghost size="large" style="margin-top: 10px;width: 100%">
            新增物品
          </a-button>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑?" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {mapState} from 'vuex'
const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 }
}
export default {
  name: 'stockAdd',
  props: {
    stockAddVisiable: {
      default: false
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    show: {
      get: function () {
        return this.stockAddVisiable
      },
      set: function () {
      }
    },
    columns () {
      return [{
        title: '物品名称',
        dataIndex: 'name',
        scopedSlots: {customRender: 'nameShow'}
      }, {
        title: '型号',
        dataIndex: 'type',
        scopedSlots: {customRender: 'typeShow'}
      }, {
        title: '数量',
        dataIndex: 'amount',
        scopedSlots: {customRender: 'amountShow'}
      }, {
        title: '所属类型',
        dataIndex: 'typeId',
        width: 200,
        scopedSlots: {customRender: 'typeIdShow'}
      }, {
        title: '单位',
        dataIndex: 'unit',
        scopedSlots: {customRender: 'unitShow'}
      }, {
        title: '单价',
        dataIndex: 'price',
        scopedSlots: {customRender: 'priceShow'}
      }]
    }
  },
  mounted () {
    this.getConsumableType()
  },
  data () {
    return {
      dataList: [],
      formItemLayout,
      form: this.$form.createForm(this),
      loading: false,
      consumableType: []
    }
  },
  methods: {
    getConsumableType () {
      this.$get('/cos/consumable-type/list').then((r) => {
        this.consumableType = r.data.data
      })
    },
    dataAdd () {
      this.dataList.push({name: '', type: '', typeId: '', unit: '', amount: '', price: ''})
    },
    reset () {
      this.loading = false
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      let price = 0
      this.dataList.forEach(item => {
        price += item.price * item.amount
      })
      this.form.validateFields((err, values) => {
        values.price = price
        values.goods = JSON.stringify(this.dataList)
        if (!err) {
          this.loading = true
          this.$post('/cos/stock-info/put', {
            ...values
          }).then((r) => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1257490.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

01-AI大模型智能客服 V0.1「上」

你好&#xff0c;我是悦创。 首发&#xff1a;https://mp.weixin.qq.com/s/6MTkpWZCEbFWOcUn0Vexvw V0.1 版本我将分为上中下三篇进行书写和发布&#xff0c;欢迎分享和我微信进讨论群&#xff1a;Jiabcdefh。 计划&#xff1a; 会迭代好几个版本&#xff0c;看阅读量和点赞…

A100 A800 H100 H800 模块

老美对A100、A800、H100和H800在内的多款AI芯片实施了出口限制&#xff0c; 目前&#xff0c;具体限制的时长并没有明确的公开信息。 科研人员在面对此类限制 &#xff0c;可能需要寻找替代的供应渠道&#xff0c;加强国内外合作&#xff0c; 或者加大在本土技术研发的投入&a…

数据结构 | 堆排序

数据结构 | 堆排序 文章目录 数据结构 | 堆排序建立大堆排序结果以及全部代码 如果没有看过堆的实现的话可以先看前面的一章堆的实现&#xff0c;然后再来看这个堆排序&#xff0c;都是比较简单的~~ 这里堆排序首先建堆&#xff0c;建堆是要建小堆还是大堆呢&#xff1f; 在堆排…

cpp中虚实继承问题

1.一个基类base&#xff0c;被类a虚继承&#xff0c;类a被其他的类继续继承&#xff0c;那么base中的初始化必须由派生类的最后一个完成&#xff0c;其中任意一个都不能代替完成基类&#xff0c;如果在最后一个派生类里不进行这个base的初始化&#xff0c;那么就会调用相应的无…

Vatee万腾的数字探险之旅:vatee科技创新的新纪元

在数字时代的潮流中&#xff0c;Vatee万腾以其独特的数字探险之旅引领着科技创新的新纪元。这不仅是一次技术的进步&#xff0c;更是一场数字领域的探险&#xff0c;让我们一同探索Vatee在科技创新中的前沿地带。 Vatee万腾的数字探险起源于对未知的渴望和对创新的不懈追求。在…

新购服务器项目部署指南—— Express + Vue + Nginx+ pm2 Nodejs项目部署全流程

目录 一、部署Express项目1.1、安装Node1.2、安装pm2进程管理器1.3、部署Express后端项目 二、部署Vue前端项目2.1、Nginx的下载安装与SLL配置2.2、打包Vue项目2.3、上传项目到Nginx目录2.4、配置Nginx 附录pm2命令速览Nginx命令速览 最后 书接上回&#xff1a;新购服务器开荒记…

不幸被封号!后续来了...

之前发文说过&#xff0c;视频号“技术领导力”被封号3天&#xff0c;无法直播了&#xff1b;购物车被禁用7天。经过多渠道申诉、跟官方沟通均无效。 对事件不了解的可以看这里《被封号了~》&#xff0c;简单来说就是转播了某位大V的直播&#xff0c;因为某些说不清道不明的原因…

快速了解软件工程学概述(5种软件过程模型)

目录 1 、什么是软件&#xff1f;特点有哪些 &#xff1f; 2 、 软件危机 定义&#xff1a; 软件危机产生的原因 消除软件危机的方法 3 、软件工程 1.软件工程的介绍 &#xff08;1&#xff09;概念 &#xff08;2&#xff09;本质特征 (3)软件工程方法学&#xff08;方…

什么样的CRM系统更值得使用?

CRM系统发展到了2023年&#xff0c;经过了无数次迭代与更新&#xff0c;各种概念开始层出不穷。当您的企业准备实施一套CRM系统&#xff0c;在选型前有个问题需要思考&#xff1a;您到底需要什么样的CRM系统&#xff1f; CRM系统早已经从当初的管理客户关系变为了“十项全能”—…

死磕MybatisPlus系列:Mapper的奇妙之旅

Mybatis Plus源码解析系列篇之Mapper的奇妙之旅 一、MybatisPlus初体验 MybatisPlus是一个基于mybatis的开源orm框架&#xff0c;其内置的Mapper、Service让开发者仅需简单的配置&#xff0c;就能获得强大的CRUD能力&#xff1b;其强大的条件构造器&#xff0c;可以满足各类需…

Walrus 0.4发布:单一配置、多态运行,体验下一代应用交付模型

今天&#xff0c;我们高兴地宣布云原生统一应用平台 Walrus 0.4 正式发布&#xff0c;这是一个里程碑式的版本更新。新版本采用了全新的应用模型——仅需进行单一配置&#xff0c;即可在多种模态的基础设施及环境中运行包括应用服务及周边依赖资源在内的完整应用系统。“You bu…

keil5下使用RAM运行程序的配置过程

本用例是展示HC32F4A0片上2M flash的擦除和读写功能&#xff0c;由于默认配置是程序写入flash中&#xff0c;并从flash中运行程序&#xff0c;所以需要将程序配置为从RAM中运行&#xff0c;这样才能正确运行此程序。默认配置如下&#xff1a; 可以看到MCU的内部flash为2M&#…

Arraylist案例

Arraylist是使用最频繁的一个集合&#xff0c;它与数组类似&#xff0c;不同之处在于它可以动态改变长度&#xff0c;不够了可以扩容。 案例&#xff1a; 我的思考&#xff1a; 首先多个菜品信息可以用Arraylist 来存储&#xff0c;那我们需要再创建一个菜品类Food&#xff0…

uni-app+ts----微信小程序锚点定位 、自动吸顶、滚动自动选择对应的锚点(点击tab跳转对应的元素位置)

uni-app----微信小程序锚点定位 、自动吸顶、滚动自动选择对应的锚点&#xff08;点击tab跳转对应的元素位置&#xff09; html代码部分 重点是给元素加入【 :id“‘item’ item.id”】 <view class"radiusz bg-white pt-[30rpx] z-[999]"><u-tabs:list&q…

长期用台灯影响视力吗?备考专用护眼台灯推荐

大家都知道台灯作为一种小范围的桌面照明灯具&#xff0c;在夜晚能给我们带来很大的帮助&#xff0c;不管是办公、还是学习、阅读都需要它提供照明。那么长期使用台灯会影响视力吗&#xff1f;其实台灯一般都眼睛都是没有伤害的&#xff0c;真正对眼睛有伤害的是不正确的使用台…

MySQL(免密登录)

简介: MySQL免密登录是一种允许用户在没有输入密码的情况下直接登录到MySQL服务器的配置。这通常是通过在登录时跳过密码验证来实现的。 1、修改MySQL的配置文件 使用vi /etc/my.cnf&#xff0c;添加到【mysqld】后面 skip-grant-tables #配置项告诉mysql跳过权限验证&#…

win10屏幕录制神器,让你轻松上手!

屏幕录制成为了人们日常生活中越来越重要的一部分&#xff0c;无论是游戏录制、在线会议记录&#xff0c;还是教程演示&#xff0c;屏幕录制都能够有效地帮助人们捕捉并分享关键信息。随着windows 10系统的普及&#xff0c;许多用户已经开始探索这个系统中的屏幕录制功能。接下…

CRM的智能招投标对企业有什么意义?

如今CRM系统的生态系统越来越壮大&#xff0c;这些工具的集成极大地丰富了CRM系统的应用场景&#xff0c;例如CRM系统集成企业微信等社交媒体为获客提供便利&#xff1b;再比如CRM集成ChatGPT提高邮件内容质量&#xff0c;对于经常接触招投标项目的业务人员来说&#xff0c;在C…

企业营销管理能够实现自动化吗?怎么做?

当今企业面临着越来越多的营销难题&#xff1a;如何有效培育潜在客户、如何提高营销活动的效果、如何优化营销资源的分配......企业的营销管理怎么做&#xff1f;或许CRM系统营销自动化会起到作用。 客户细分&#xff1a; 企业可以通过CRM的客户细分功能&#xff0c;根据客户…