使用vuex存储数据mapActions,mapState

发现使用

import { mapGetters } from 'vuex' 

获取数据

与此种方法获取数据得到的结果不一样。


import { createNamespacedHelpers } from 'vuex'
const { mapActions, mapState } = createNamespacedHelpers('my')

大概是js文件写法的问题,,有时间再研究。

还是要会自己写代码,存粹照搬别人代码bug简直百出。。。

my.js

import {
  AddDepartment
} from '@/api/search'
import axios from 'axios'
// eslint-disable-next-line no-irregular-whitespace
// export default {
const my = {
  namespaced: true, // 命名空间
  // state: {
  //   ceshi: 1
  // },

  // mutations: {
  //   CESHI_NUM: (state, data) => {
  //     state.ceshi += data
  //   }
  // },

  // actions: {
  //   ceshi({
  //     commit,
  //     state
  //   }, data) {
  //     commit('CESHI_NUM', data)
  //   }
  // }
  state: {
    // deparments: []
    AddDepartmentData: []
  },

  actions: {
    AddDepart(context) {
      // AddDepartment()
      axios.get('/departments')
        .then(res => {
          debugger
          context.commit('AddDepart', res)
          console.log(res.data.data.list)
          alert('888')
        })
        .catch(error => {
          console.log(error)
        })
    }
  },
  mutations: {
    AddDepart(state, res) {
      state.AddDepartmentData = res.data.data.list
      console.log(state.AddDepartmentData)
    }
  }
}
export default my

html页面

<template>
  <div>
    <div v-show="isShow" class="content">
      <div class="title">
        <h3 class="tab-title">部门列表</h3>
        <el-button
          type="primary"
          :class="{'selected':tab === 1,'testTitle':true}"
          @click="toTab('deparapment')"
        >部门添加</el-button>
      </div>
      <div>原stor中注册的为:{{ AddDepartmentData }}</div>
      <!-- <el-button type="primary" icon="el-icon-search" @click="change_vuex">测试vuex</el-button>
    <el-button type="primary" icon="el-icon-search" @click="change_vuex_ansnc">异步测试vuex</el-button> -->
      <el-table
        :data=" tableData "
        class="tab"
        row-key="departmentId"
        border
        lazy
        :load="load"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="departmentId" label="ID" width="180" />
        <el-table-column prop="departmentName" label="部门名称" width="480" />
        <el-table-column prop="userCount" label="职员数量" width="180" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="info" plain @click="toTab('DepartmentModify')">
              <!-- @click="handleEdit(scope.$index, scope.row)" -->
              <i class="el-icon-edit-outline" />
            </el-button>
            <el-button size="mini" type="info" plain @click.prevent="del(scope.$index, scope.row)">
              <!-- @click="remove(scope.$index, scope.row)" -->
              <i class="el-icon-delete" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--弹窗-->
      <el-dialog :title="dialogTitle" width="50%" :visible.sync="iconFormVisible">
        <el-form :inline="true" :model="userInfo" class="demo-form-inline">
          <el-form-item label="部门名称">
            <el-input v-model="userInfo.date" placeholder="部门名称" />
          </el-form-item>
          <el-form-item label="职员数量">
            <el-input v-model="userInfo.number" placeholder="职员数量" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="iconFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUser()">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <deparapment ref="deparapment" @gohome="gohome" />
    <DepartmentModify ref="DepartmentModify" @gohome="gohome" />
  </div>
</template>
<script>
// import { searchApi } from '../../api/search'
import * as searchApi from '@/api/search'
import deparapment from './components/deparament'
import DepartmentModify from './components/DepartmentModify'

import { createNamespacedHelpers } from 'vuex'
const { mapActions, mapState } = createNamespacedHelpers('my')
// console.log(mapState(['AddDepartmentData']), '----')
export default {
  components: {
    deparapment,
    DepartmentModify
  },
  data() {
    return {
      name: 'ExportExcel',
      isShow: true,
      tableData: [],
      treeDate: [],
      tab: '',
      iconFormVisible: false,
      userInfo: {},
      dialogTitle: '增加',
      rowIndex: null,
      tableData1: [
        {
          id: 1,
          date: '深圳市中鹏教育科技股份有限公司',
          number: '1',
          hasChildren: true
        }
      ],

      menu_list: [{
        id: '1',
        menu_name: '设置',
        menu_url: 'setting',
        parent_id: 0
      }, {
        id: '1-1',
        menu_name: '权限设置',
        menu_url: 'setting.permission',
        parent_id: '1'
      }, {
        id: '1-1-1',
        menu_name: '用户管理列表',
        menu_url: 'setting.permission.user_list',
        parent_id: '1-1'
      }, {
        id: '1-1-2',
        menu_name: '用户管理新增',
        menu_url: 'setting.permission.user_add',
        parent_id: '1-1'
      }, {
        id: '1-1-3',
        menu_name: '角色管理列表',
        menu_url: 'setting.permission.role_list',
        parent_id: '1-1'
      }, {
        id: '1-2',
        menu_name: '菜单设置',
        menu_url: 'setting.menu',
        parent_id: '1'
      }, {
        id: '1-2-1',
        menu_name: '菜单列表',
        menu_url: 'setting.menu.menu_list',
        parent_id: '1-2'
      }, {
        id: '1-2-2',
        menu_name: '菜单添加',
        menu_url: 'setting.menu.menu_add',
        parent_id: '1-2'
      }, {
        id: '2',
        menu_name: '订单',
        menu_url: 'order',
        parent_id: 0
      }, {
        id: '2-1',
        menu_name: '报单审核',
        menu_url: 'order.orderreview',
        parent_id: '2'
      }, {
        id: '2-2',
        menu_name: '退款管理',
        menu_url: 'order.refundmanagement',
        parent_id: '2'
      }]
    }
  },
  computed: {
    ...mapState(['AddDepartmentData'])
  },
  mounted() {
    this.getAllList()
    console.log(this.$store)
    this.AddDepart()
    console.log(this.AddDepartmentData, '----')
  },
  methods: {
    ...mapActions([
      'AddDepart' // 触发actions里的 getInfo 函数,调动接口
    ]),
    gohome(obj) {
      console.log('子组件传过来', obj)
      this.isShow = true
    },
    getAllList() {
      // searchApi.AddDepartment()
      //   .then(response => {
      //     // console.log('tst')
      //     // console.log(response)
      //     const l = response.data
      //     // this.treeDate2 = this.buildTree(l.list)
      //     // console.log([this.treeDate2])
      //     // this.treeDate.push(this.treeDate2)
      //     // console.log(this.treeDate)

      //     this.tableData = response.data.list
      //   }).catch(error => {
      //     console.log(error)
      //   })
    },
    buildTree(list) {
      const temp = {}
      const tree = {}
      for (const i in list) {
        temp[list[i].departmentId] = list[i]
      }
      for (const i in temp) {
        if (temp[i].parentId) {
          if (!temp[temp[i].parentId].children) {
            // eslint-disable-next-line no-new-object
            // eslint-disable-next-line no-array-constructor
            temp[temp[i].parentId].children = new Array()
          }
          temp[temp[i].parentId].children[temp[i].departmentId] = temp[i]
        } else {
          tree[temp[i].departmentId] = temp[i]
        }
      }
      return tree
    },
    del(index, row) { // 删除
    // debugger
      this.$http.delete('/department/' + index).then(result => {
        // console.log(index)
        // console.log(result)
        this.li = this.tableData[index].departmentId
        this.li = index
        this.name = this.tableData[index].departmentName
        this.$confirm(`确定删除【${this.name}】部门吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          if (result.data.code === 2000) {
          // 删除成功

            // this.tableData.forEach(function(item, index, arr) {
            console.log(666)
            // console.log(index)

            // console.log(this.index)
            console.log(this)
            // console.log(this.tableData[index].departmentId)
            this.tableData.splice(this.li, 1)
            console.log(this.tableData)

            // })
            console.log('删除成功')
            // this.getAllList()
          } else {
            alert('删除失败!')
            // his.$message.error(errMsg)
          }
        })
      }).catch(error => {
        console.log(error)
      })
    },
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve([
          {
            id: 31,
            date: '董事会',
            number: '5'
          },
          {
            id: 32,
            date: '行业工作事业部',
            number: '10'
          }
        ])
      }, 1000)
    },
    // 删除行
    handleDelete(index, rows) {
      rows.splice(index, 1)
    },
    // 增加
    add() {
      this.dialogTitle = '增加'
      this.userInfo = {}
      this.iconFormVisible = true
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogTitle = '编辑'
      this.userInfo = row
      this.iconFormVisible = true
      this.rowIndex = index
    },
    // 弹窗确定
    submitUser() {
      if (this.dialogTitle === '编辑') {
        this.tableData1.splice(this.rowIndex, 1, this.userInfo)
        this.iconFormVisible = false
        return
      }
      this.tableData1.splice(0, 0, this.userInfo)
      this.iconFormVisible = false
    },
    // 删除
    remove(index, row) {
      // debugger
      // console.log(row)
      // console.log(row.date)
      this.$confirm(`确定删除${row.date}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.tableData1.splice(index, 1)
      })
    },
    toTab(name, subname) {
      // this.$refs[subname].isShow = false;
      this.isShow = false
      this.$nextTick(() => {
        this.$refs[name].isShow = true
      })
    }
  }
}
</script>
<style lang="scss"  scoped>
>>>.el-button--medium {
  padding: 8px 13px;
  font-size: 12px;
  float: right;
  margin-top: 8px;
}
.title {
  width: 99%;
  height: 32px;
  line-height: 35px;
  margin: 0 auto;
  padding-bottom: 5px;
}
.content {
  width: 98%;
  border: 1px solid #b3cdda;
  margin: 0 auto;
  margin-top: 10px;
  padding-bottom: 20px;
  border-radius: 5px;
}
.tab {
  width: 99%;
  // border: 1px solid #fff;
  margin: 0 auto;
  margin-top: 10px;
}
.tab-title {
  color: #525759;
  display: contents;
}
.main-footer {
  height: 60px;
  line-height: 40px;
  position: fixed;
  float: right;
  z-index: 10;
  right: 0;
  bottom: 0;
  width: 86.5%;
color: #525759;
  margin: 0; /*很重要*/
}
.main-footer span{
  margin-left: 10px;
}
.versions{
  float: right;
  margin-right: 10px;
}
>>> .el-table thead {
    color: #131314 !important;
}
>>> .el-button--medium {
    margin-top: 5px!important;
    margin-left: 20px!important;
}

</style>

结果打印出来了:

发布了98 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42416812/article/details/103751669