In vUE project, ztree plug-in is used to realize the function of adding, deleting, changing and checking, and to achieve the secondary encapsulation of the function of adding, deleting, changing and checking.

How to use ZTree in vUE project

  1. Download ztree

Download the Ztree plugin from the official website, and put the corresponding JS and CSS files into the Vue project.

  1. The introduction of

The main.js entry file is introduced in the vue project

import $ from 'jquery';
import '@/assets/js/ztree/zTreeStyle/zTreeStyle.css';
import './assets/js/ztree/jquery.ztree.core.js';
import './assets/js/ztree/jquery.ztree.excheck.js';
import './assets/js/ztree/jquery.ztree.exedit.js';
Copy the code
  1. configuration

This is done in vue.config.js of the vue project.

module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery'.jQuery: 'jquery'.'windows.jQuery': 'jquery'}})]},Copy the code
  1. use

Complete the steps above to use ZTree.

Achieve results

Ztree components

HTML part

<template>
  <div class="objZtree">
    <div class="split-body">
      <div class="split-content">
        <ul id="objTree" class="ztree" style="min-height: 500px"></ul>
      </div>
    </div>
  </div>
</template>
Copy the code

Js part

<script>
// import $ from 'jquery';
import './iconfont.css';
export default {
  props: {
    searchedData: {
      type: Array}},data() {
    return {
      setting: {
        view: {
          // Display ICONS
          showIcon: true.// Triggered when the mouse moves over the node
          addHoverDom: this.addHoverDom,
          // Triggered when the mouse removes a node
          removeHoverDom: this.removeHoverDom,
          // Set the node font style
          fontCss: {
            margin: '6px'}},edit: {
          enable: true.// Whether to display the default delete button
          showRemoveBtn: false.showRenameBtn: false
        },
        callback: {
          // Ztree default delete button - called before delete
          // beforeRemove: this.beforeRemove
          // Click the expand button to send the request - call before sending the request
          beforeAsync: this.beforeAsync,
          // The asynchronous request was successfully invoked
          onAsyncSuccess: this.zTreeOnAsyncSuccess,
          // Called when a node is clicked - This component is used to view node content
          onClick: this.zTreeOnClick
        },
        data: {
          // The name of the data field used to specify the node display name
          key: {
            name: 'name'}},async: {
          // Set up asynchronous requests
          enable: true.// The requested URL
          url: function (treeId, treeNode) {
            // console.log(' asynchronous request ', treeId, treeNode); // Get information about the current node
            return './index.vue';
          },
          type: 'GET'}},// Initialize node data
      initalNode: [].currentTreeId: ' '.currentTreeNode: []}; },created() {
    this.getTreeCate();
  },
  methods: {
    // Initialize the ztree function
    loadObjTree() {
      $.fn.zTree.init($('#objTree'), this.setting, this.initalNode);
    },
    beforeAsync(treeId, treeNode) {
      console.log('Triggered before asynchronous request is sent', treeId, treeNode);
    },
    zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
      console.log('Asynchronous request successful callback function execution', event, treeId, treeNode, msg);
      // Add a node to ztree
      // zTree.addNodes(treeNode, msg);
    },
    zTreeOnClick(event, treeId, treeNode) {
      // The function that fires when a node is clicked
      let zTree = $.fn.zTree.getZTreeObj(treeId);
      let selectedNodes = zTree.getSelectedNodes(true); // Get the node clicked (the selected node)
      this.$emit('changeViewVisible', selectedNodes[0], selectedNodes[0].level);
    },
    addHoverDom(treeId, treeNode) {
      this.currentTreeId = treeId;
      this.currentTreeNode = treeNode;
      var aObj = $(The '#' + treeNode.tId + '_span');
      if ($('#diyBtnGroup').length > 0) return;
      let editStr;
      // Customize icon styles
      if (treeNode.level === 0) {
        editStr = `<span id='diyBtnGroup'> <i class="iconfont icon-tianjia" style="color: #1296db; margin-left: 5px;" id='diyBtn_${treeNode.id}_add '&western nClick =' enclosing the blur (); '></i> </span>`;
      } else if (treeNode.level === 1) {
        editStr = `<span id='diyBtnGroup'> <i class="iconfont icon-bianji" style="color: #1296db; margin-left: 5px;" id='diyBtn_${treeNode.id}_modify '&western nClick =' enclosing the blur (); '></i> <i class="iconfont icon-cangpeitubiao_shanchu" style="color: #1296db; margin-left: 5px;" id='diyBtn_${treeNode.id}_delete '&western nClick =' enclosing the blur (); '></i> </span>`;
      }
      aObj.append(editStr); // Add custom button groups after each node
      var btnDelete = $('#diyBtn_' + treeNode.id + '_delete');
      var btnAdd = $('#diyBtn_' + treeNode.id + '_add');
      var btnModify = $('#diyBtn_' + treeNode.id + '_modify');
      if (btnDelete) {
        btnDelete.bind('click'.(e) = > {
          // Trigger the parent component's method to make the delete dialog box display
          this.$emit('delConfirm');
        });
      }
      if (btnAdd) {
        btnAdd.bind('click'.(e) = > {
          e.stopPropagation();
          this.$emit('changeAddFormVisible', treeNode);
        });
      }
      if (btnModify) {
        btnModify.bind('click'.(e) = > {
          e.stopPropagation();
          this.$emit('changeModifyVisible', treeNode, true); }); }},// Delete the previously called logic
    // beforeRemove(e) {
    // console.log(e);
    // alert(' are you sure you want to delete ');
    // },

    $refs.ztreeref.delNode (); // This.$refs.ztreeref.delnode ();
    delNode() {
      var treeObj = $.fn.zTree.getZTreeObj(this.currentTreeId);
      var nodes = treeObj.getSelectedNodes();
      // Send a request to delete the node
      this.$http.delete('/dg/api/v1/datasources/' + nodes[0].id).then((res) = > {
        if (res.code === 0) {
          this.$Message.success('Classification deleted successfully');
          this.getTreeCate();
        } else {
          this.$Message.error('Failed to delete category'); }}); },addNode(newAddInfo) {
      console.log('New Information', newAddInfo);
      letnewAddDbParams = { ... newAddInfo };console.log('newAddDbParams', newAddDbParams);
      this.$http.post('/dg/api/v1/datasources', newAddDbParams).then((res) = > {
        console.log('New node', res);
        if (res.code === 0) {
          this.$Message.success('New node added successfully! ');
          this.$emit('handleReset');
          // Add nodes by resending requests for data
          this.getTreeCate();
        } else {
          this.$Message.error({
            content: res.msg,
            duration: 10.closable: true}); }});// var add = treeObj.addNodes(nodes[0], newAddNodeParams); // add a new node under the parentNode. If parentNode is null, the parentNode is added
      // console.log(' return value after new node ', add); // Return the new node as an array
    },
    // Modify node information
    modifyNode(updatedinfo) {
      console.log('Modified information', updatedinfo, this.currentTreeNode);
      // Data parameters to be sent to the background
      letmodifyDbParams = { ... updatedinfo,modifyDepartment: ' '.modifyTime: ' '.modifyUser: ' '
      };
      console.log('Modify parameter Transfer', modifyDbParams);
      this.$http.put('/dg/api/v1/datasources', modifyDbParams).then((res) = > {
        if (res.code === 0) {
          this.$Message.success('Node modified successfully! ');
          this.getTreeCate();
          // Shadow change box
          this.$emit('changeModifyVisible'[],false);
        } else {
          this.$Message.error('Failed to modify node'); }}); },// Mouse away from the current node logic
    removeHoverDom: (treeId, treeNode) = > {
      #diyBtnGroup = #diyBtnGroup = #diyBtnGroup
      $('#diyBtnGroup').unbind().remove();
    },
    // Get classified data
    getTreeCate() {
      // Send a request to get the initial data from ZTree
      this.$http.get('/dg/api/v1/datasources/type').then((res) = > {
        if (res.code === 0) {
          // The icon before adding a node
          this.initalNode = this.addIcon(res.data);
          console.log('New icon'.this.addIcon(res.data));
          localStorage.setItem('initDbData'.JSON.stringify(res.data));
          // Initialize ztree (); // Initialize ztree ()
          this.loadObjTree(); }}); },addIcon(treeNodeData) {
      return treeNodeData.map((item) = > {
        item.icon = 'https://s3.ax1x.com/2021/01/09/sMM9MQ.png';
        item.iconSkin = 'icon1';
        // Add ICONS for secondary nodes
        if (item.children.length > 0) {
          item.children.forEach((item1) = > {
            item1.icon = 'https://s3.ax1x.com/2021/01/09/sM1JJ0.png';
            item1.iconSkin = 'icon2';
          });
        }
        returnitem; }); }},mounted() {
    // this.loadObjTree();
  },
  computed: {},
  watch: {
    // Query operation -- listen to the parent component after the query operation, get the latest data, reload ztree
    searchedData(newInfo, oldInfo) {
      this.initalNode = newInfo;
      this.loadObjTree(); }}}; </script>Copy the code

The CSS part

/* Modify the icon style -- global import */
.ztree li span.button.icon1_ico_open..ztree li span.button.icon1_ico_close {
  background: url("https://s3.ax1x.com/2021/01/09/sMM9MQ.png") 0 0 no-repeat;
  background-size: 23px 20px;
  width: 30px;
  height: 22px;
}
.ztree li span.button.icon2_ico_open..ztree li span.button.icon2_ico_close {
  background: url("https://s3.ax1x.com/2021/01/09/sMM9MQ.png") 0 0 no-repeat;
  background-size: 23px 20px;
  width: 30px;
  height: 22px;
}
Copy the code

Using Ztree

Import — component Ztree

    <Ztree
      @changeAddFormVisible="changeAddFormVisible"
      @changeViewVisible="changeViewVisible"
      @handleReset="handleReset"
      @changeModifyVisible="changemodifyDbFormVisible"
      @delConfirm="delConfirm"
      :searchedData="searchedData"
      ref="ZtreeRef"
      />
Copy the code

api

  1. event
  • changeAddFormVisible(treeNode)
  • ChangeViewVisible (selectedNode, selectedNodeLevel) // parameters: click the selectedNode and select the level of the node
  • ChangeModifyVisible (treeNode, visible)
  • DelConfirm (): Click delete, the deletion confirmation box will pop up
  • HandleReset (): Call the reset form method after successfully adding data
  1. Attribute data:
  • EarchedData (): Listens for data changes found in the parent component and reloads the tree
  1. Ref: The request address and request parameters in zTree need to be manually modified
  • ZtreeRef delNode() addNode(newAddInfo) modifyNode(updatedinfo)

When adding, deleting, or modifying data, you need to send requests to the background. I put the part of sending the request in ztree component, so I need to manually modify the request address and request parameters in ZTree component

Using an example

delete

// Call delConfirm in ztree to display the delete confirmation dialog box
  delConfirm () {
    this.$Modal.confirm({
        title: 'Confirm deletion'.content: '

Are you sure you want to remove this node?

'
.onOk: () = > { // After clicking delete ok, call the delete node operation defined in Ztree this.$refs.ZtreeRef.delNode(); this.checkBoxVisible = false; this.addDbFormVisible = false; this.modifyDbFormVisible = false; }, onCancel: () = > { this.$Message.info('Cancel delete! '); }}); }Copy the code

Modify the

 changemodifyDbFormVisible(currentNode, isVisible) {
    // Displays the hidden modification form
 	this.modifyDbFormVisible = isVisible;
 	// Backfill the form entry based on the currentNode value
 },
modifyDbSubmit() {
	// When the modification form validates
    this.$refs.modifyDbFormRef.validate((valid) = > {
      if (valid) {
      	// Call modifyNode in zTree and pass the modified information. Ztree sends a request to commit the modified content.
        this.$refs.ZtreeRef.modifyNode(modifyDbFormInfo);
      } else {
        this.$Message.error('Fail! '); }}); },Copy the code