[Vuejs]-How to update a tree without refreshing whole page?

0👍

The solution contains a few steps:

  1. use "go-echo-vue" for communication between backend and frontend like here: https://github.com/covrom/go-echo-vue

  2. update zTree data using vue-resource and timer like this:

     <script>
     new Vue({
         // ....
         methods: {
             updateZNodes() {
                 // запрашиваем дерево :)
                 this.$http.get('/znodes').then(function (response) {
                     zNodes = response.data.items ? response.data.items : []
                 }, function (error) {
                     console.log(error)
                 });
             },
         },
         mounted() {
             setInterval(() => {
                 this.updateZNodes();
             }, 5000);
         },
         // ....
     })</script>
    
  3. refrest zTree nodes information using js:

     <script language="JavaScript">
             function refreshNode() {
             var treeObj = $.fn.zTree.getZTreeObj("tree");
             var nodes = treeObj.getNodes();
             if (nodes.length > 0) {
                 for (let i = 0; i < nodes.length; i++) {
                     c = "static/css/zTreeStyle/img/diy/c16grey.png";
                     if (zNodes.length >= i) {
                         c = zNodes[i].icon
                     }
                     nodes[i].icon = c;
                     treeObj.updateNode(nodes[i]);
                 }
             }
         };
    
         const timerId = setInterval(
             () => {
                 refreshNode();
             },
             5000
         );
     </script>
    
  4. add async zTree settings:

     <script language="JavaScript">
         var setting = {
             // ....
             async: {
                 enable: true,
                 url: "",
                 autoparam: ["id", "icon"],
                 datatype: "json",
             },
             // ....
         };
     </script>
    

That’s all. So we have Vue function http.get to get fresh data from backend, global js variable to use that data both inside Vue code segment and JavaScript blocks.

PS additional information: https://www.tutorialfor.com/blog-188266.htm

Leave a comment