Iview组件库之tree的第二种实现

2,112 阅读2分钟

Iview组件库之tree

让我们看一下实现的效果

效果

通过Iview组件库中的tree的on-select-change事件实现。 点击树节点时触发,可以返回当前已选中的节点数组、当前项

我们需要写两个组件

树组件

三个按钮,一个用来添加,一个用来修改,一个用来删除

<template>
  <Card ref="cardTable">
      <Button type="info" size="small"  icon="md-add" @click="handleAdd(currentNode,currentRoot)">添加</Button>
      <Button type="primary" size="small" icon="md-create" @click="handleEdit(currentNode,currentRoot)">修改</Button>
      <Button type="error" size="small" icon="md-close" @click="handleDelete(currentNode,currentRoot)">删除</Button>
      <tree :data="treeData"  @on-select-change="handleSelectChange" ref="tree">
      </tree>
      <ColumnFormModal
      :currentColumnParent="currentColumnParent"
      :currentNodeKey="currentNodeKey"
      :showModal="showModal"
      :treeObj="treeObj"
      @modal-visible-change="modalVisibleChange"
      ></ColumnFormModal>
  </Card>
</template>

<script>
import ColumnFormModal from './ColumnFormModal'
export default {
  name: 'Column',
  components: {
    ColumnFormModal
  },
  data () {
    return {
      // 用来给tree的data属性赋值
      treeData: [],
      // 用来接收后台传来的树List
      treeList: null,
      // 编辑模态框
      showModal: false,
      // 选中的当前node
      currentNode: {},
      // 选中的树的根节点
      currentRoot: {},
      // 树对象
      treeObj: {},
      // 当前选中节点的nodeKey
      currentNodeKey: 0,
      // 当前选中节点的父节点的nodeKey
      currentColumnParent: 0
    }
  },
  props: {},
  computed: {},
  methods: {
    // 响应弹窗的变化
    modalVisibleChange (visible) {
      this.showModal = visible
      // 递归查询树结构
      this.initTreeList()
    },
    // 选中树节点触发的方法
    handleSelectChange (root, node) {
      this.currentNode = node
      this.currentRoot = root
    },
    // 新增按钮触发的方法
    handleAdd (currentNode) {
      console.log(currentNode)
      // 声明一个数组
      let treeNode = currentNode.children ? currentNode.children : []
      // console.log(treeNode)
      // 声明一个对象
      let column = {}
      // 新增节点,新增的节点的名字是 ‘新增节点’
      // 修改名字需要点击修改按钮
      treeNode.push({
        title: '新增节点',
        parent: currentNode.id,
        expend: true,
        isEdit: false,
        children: []
      })
      column.columnTitle = treeNode[treeNode.length - 1].title
      column.columnParent = treeNode[treeNode.length - 1].parent
      column.childColumn = []
      column.nodeKey = currentNode.nodeKey
      console.log(column)
      this.saveOrUpdateColumn(column)
    },
    // 编辑按钮触发的方法
    handleEdit (currentNode, currentRoot) {
      this.showModal = true
      this.treeObj = Object.assign({}, currentNode)
      console.log(currentNode)
      this.currentColumnParent = currentNode.columnParent
      this.currentNodeKey = currentNode.nodeKey
      console.log(this.currentColumnParent)
      console.log(this.currentNodeKey)
    },
    // 删除按钮触发的方法
    handleDelete (currentNode, currentRoot) {
      let id = currentNode.id
      this.deleteColumn(id)
      this.initTreeList()
    },
    // 查询树结构
    initTreeList () {
      this.axios.request('GET', '接口').then(response => {
        if (response.status === 200) {
          this.treeList = response.data
          this.getTree(this.treeList)
          this.treeData = this.treeList
        }
      })
    },
    // 递归解析树结构
    getTree (parents) {
      if (parents === undefined) {
        return
      }
      parents.forEach(item => {
        item.title = item.columnTitle
        item.children = item.childColumn
        this.getTree(item.childColumn)
      })
    },
    // 调用后台新增或者编辑的接口
    // 参数是实体
    saveOrUpdateColumn (column) {
      this.axios.request('POST', '接口', column).then((response) => {
        let status = response.status
        if (status === 200) {
          this.initTreeList()
        } else {
        // 提示错误
          let errorMsg = '[' + response.errorCode + ']:' + response.errorMsg
          this.$Notice.error({
            title: '错误',
            desc: errorMsg,
            duration: 5
          })
        }
      })
    },
    // 调用后台删除的接口
    // 根据id删除
    deleteColumn (id) {
      this.axios.request('POST', '接口', {id}).then(response => {
        let status = response.status
        if (status === 200) {
          this.initTreeList()
        } else {
        // 提示错误
          let errorMsg = '[' + response.errorCode + ']:' + response.errorMsg
          this.$Notice.error({
            title: '错误',
            desc: errorMsg,
            duration: 5
          })
        }
      })
    }
  },
  watch: {
    showModal (val) {
      this.visible = val
    },
    visible (val) {
      this.$emit('modal-visible-change', val)
    }
  },
  created () {
     // 查询树
    this.initTreeList()
  },
  mounted () {
  }
}
</script>

<style>

</style>

模态框

<template>
 <div>
   <Modal
    v-model="visible"
    title='编辑'
     @on-visible-change="visibleChange"
     :mask-closable="false">
     <Form ref="form" :model="columnModal" :label-with="80">
       <FormItem prop="columnTitle" label="栏目名称">
         <Input v-model="columnModal.columnTitle"/>
       </FormItem>
     </Form>
       <div slot="footer">
      <Button @click="cancel" :disabled="requestLoading">取消</Button>
      <Button type="primary" @click="submit" :loading="requestLoading">{{requestLoading ? '正在提交' : '提交'}}</Button>
    </div>
   </Modal>
 </div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  name: 'ColumnFormModal',
  components: {},
  data () {
    return {
      visible: false,
      columnModal: {}
    }
  },
  props: {
    showModal: {
      type: Boolean,
      required: true
    },
    processObj: {
      type: Object,
      required: false
    },
    currentNodeKey: {
      type: Number | Object,
      required: true
    },
    currentColumnParent: {
      type: Number | Object,
      required: true
    }
  },
  computed: {
    ...mapGetters([
      'requestLoading'
    ])
  },
  methods: {
    // 响应显示与否
    visibleChange (status) {
      // 显示时初始化动作
      if (status) {

      } else {
        // 关闭时抛出事件
        this.$emit('modal-visible-change', false)
      }
    },
    // 提交
    submit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.columnModal.columnParent = this.currentColumnParent
          this.columnModal.nodeKey = this.currentNodeKey
          console.log(this.columnModal)
          this.axios.request('POST', 'message/column/saveOrUpdateColumn', this.columnModal).then((response) => {
            let status = response.status
            if (status === 200) {
              this.$Notice.success({
                title: '栏目编辑' + '成功',
                duration: 3
              })
              this.$emit('on-oper-success', this.columnModal)
            } else {
              // 提示错误
              let errorMsg = '[' + response.errorCode + ']:' + response.errorMsg
              this.$Notice.error({
                title: '栏目编辑' + '失败',
                desc: errorMsg,
                duration: 5
              })
            }
          }).finally(() => {
            this.visible = false
          })
        }
      })
    },
    cancel () {
      this.visible = false
      // 清空校验信息
      this.$refs['form'].resetFields()
      // 关闭时抛出事件
      this.$emit('modal-visible-change', false)
    }
  },
  watch: {
    showModal (val) {
      this.visible = val
      this.columnModal = Object.assign({}, this.treeObj)
    },
    visible (val) {
      this.$emit('modal-visible-change', val)
    }
  },
  created () {},
  mounted () {}
}
</script>

<style>

</style>

github github.com/zhangzhemin…

博客 zhangzheming.club/2019/03/30/…