Do not rely on any third party, simply use Vue to realize Tree tree control.

Received a demand these days, there is a need to do a property component, looking for a third party, but can not fully meet my needs, there is time, I do a small wheel it.

Let’s look at the renderings first.The font icon used before the red dot is a right sign. Here, for convenience, the circle is used instead of the selected state, so it is not very good-looking. It needs to be modified by itself.

I directly use vue-cli to build the project, the code directory is as follows:

The way of use is as follows:

treeDataThe format is as follows:

treeData: [
        {open: false, name: '1', level: 0, checked: true},
        {
          open: false, // opend  Whether to unfold subsetName:'2',Level: 0, //level represents the first layer.Checked: false, / / checked generationIs table checked?Children: [{Open: false,Name:'3',Level: 1,Checked: false,Children: [{open: fAlse, name:'4', level: 2, checked: false},{Open: false,Name:'5',Level: 2,Checked: false}]}]}]

This component is designed to several key points as follows:

1. Depth Watch

Because the data is a deep object, so simple watch, can not detect changes in the data, so the use of deep, the code is as follows:

watch: {
    // Deep monitoring of treeDate data changes using deepTreeData: {Handler: function (newVal, oldVal) {This.caLculateSelectFormResult ()},Deep: true}}

2.recursion

The results of the data are recursively traversed.

calculateSelectFormResult: function () {
      var arr = []
      function f (obj) {
        for (var i in obj) {
          if (obj[i].checked) {
            // console.log(2)
            arr.push(obj[i].name)
          }
          if (obj[i].children) {
            if (obj[i].children.length !== 0) {
              f(obj[i].children)
            }
          }
        }
      }
      f(this.treeData)
      this.selectFormResult = arr
      console.log(this.selectFormResult)
    }

3.Simulation of slideDown slideUp animation effect

 

Project complete code address: https://github.com/YalongYan/tree

Leave a Reply

Your email address will not be published. Required fields are marked *