Home > Web Front-end > JS Tutorial > body text

How to dynamically refresh tables using vue2.0 combined with the DataTable plug-in

高洛峰
Release: 2017-03-19 09:54:55
Original
2886 people have browsed it

This article mainly introduces the method of vue2.0 combined with the DataTable plug-in to achieve dynamic table refresh. It analyzes the problems encountered in the process of vue2.0 combined with the DataTable plug-in to achieve dynamic table refresh and the corresponding solutions based on specific project examples. , Friends in need can refer to

This article describes the method of dynamically refreshing tables using vue2.0 combined with the DataTable plug-in. Share it with everyone for your reference. The details are as follows:

The requirements put forward by the product are as follows. It is a very common table that counts the completion rate and status of server-side tasks. The data in it must be automatically refreshed, and when a single task When completed, report to the server. It seems such an easy request! Hear me out!

What I use here is the framework is vue, the table is naturally rendered with v-for, and then our sidepagination Search Shenma is all done by the front end, which means that the back end just stuffs a lot of data into the front end, and then the front end assembles the pager and completes the fuzzy search by itself. So, I used the DataTable plug-in before. The effect of the assembled form is as follows, it looks fine!

How to dynamically refresh tables using vue2.0 combined with the DataTable plug-in

But there is a problem when it comes to automatic refresh, because every time the data is obtained, it is the full amount of data. If you use dataTable to assemble the table, you must destroy the assembled table. , then v-for and then DataTable() assembly... the page will keep flashing! What a terrible experience!

I just came up with a relatively stupid way to solve this partial refresh problem. If you have a better way, please tell me! ! Get on the code!

1.v-for only renders unchanged data, such as name notes and the like. Fields that are constantly refreshed, such as status and completion rate, are empty. That's it, only use DataTable to render the table for the first time

2.setRefresh is a timer, which calls itself recursively every 1s, queries the full amount of data, and stores it in the originTableList

3.updateRefreshStatus is Use native js to get the dom of each row, and then innerText to change its value

4.reportTaskComplete is to report to the server when the completion rate of the current task reaches 100%

5.checkTaskRefresh is Check all tasks recursively and put the completed tasks into completeTaskList. If all are completed, clear the timer

6.beforeRouteLeave is the method of vue router, after leaving the route Clear timer

template


<template>
  <p class="row">
    <loadingHourGlass></loadingHourGlass>
    <p class="col-xs-12 top-offset-15 bottom-offset-15">
      <p>
        <strong class="pull-left line-height-24 right-offset-15">自动刷新开关:</strong>
        <iphoneSwitcher v-bind:status="refresh.status" v-bind:canSwitch="false" v-bind:callBackName="&#39;switchRefreshStatus&#39;"></iphoneSwitcher>
      </p>
      <button type="button" class="btn btn-sm btn-primary pull-right" v-on:click="editRecord()">添加任务</button>
    </p>
    <p class="col-xs-12 main-table-wrapper">
      <h4 class="page-header">点播刷新任务数据表格 <!-- <small>Secondary text</small> --></h4>
      <!-- <p>123</p> -->
      <table class="table table-striped table-hover table-bordered" id="main-table">
        <thead>
          <tr>
            <th>名称</th>
            <th>状态</th>
            <th>完成率</th>
            <th>创建时间</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody><!-- v-bind:class=" (item.completeCount/item.total==&#39;1&#39;)?&#39;text-success&#39;:&#39;text-danger&#39; " -->
          <tr v-for="item in tableList" v-bind:class="&#39;id-&#39; + item.id">
            <td>{{ item.file_name }}</td>
            <!-- {{ item.status | statusFilter }} -->
            <td class="status"></td>
            <!-- v-bind:class=" (item.completeCount/item.total==&#39;1&#39;)?&#39;text-success&#39;:&#39;text-danger&#39; " -->
            <!-- {{ item.completeRate }} -->
            <td class="rate"></td>
            <td>{{ item.create_time }}</td>
            <td>{{ item.description }}</td>
            <td>
              <button type="button" class="btn btn-primary btn-xs" v-on:click="showDetailModal(item.id,item.file_name)">详情</button>
              <!-- <button type="button" class="btn btn-danger btn-xs" v-on:click="test()">test</button> -->
            </td>
          </tr>
        </tbody>
      </table>
    </p>
  </p>
</template>
Copy after login


##js


methods: {
  initRecordTable: function(){
    $(&#39;#main-table&#39;).DataTable({
      "paging": true,// 开启分页
      "pageLength": 10,//每页显示数量
      "lengthChange": true,//是否允许用户改变表格每页显示的记录数
      "searching": true,//搜索
      "ordering": true,//排序
      "info": true,//左下角 从 1 到 5 /共 23 条数据
      "autoWidth": true,
      // "scrollX": "100%",//表格的宽度
      // "scrollY": "200px",//表格的高度
      "scrollXInner": "100%",//表格的内容宽度
      // "bScrollCollapse":true,//当显示的数据不足以支撑表格的默认的高度时,依然显示纵向的滚动条。(默认是false)
      "aaSorting": [
        [3, &#39;asc&#39;]
      ],
      "language": {
        "sInfoEmpty": "没有数据",
        "sZeroRecords": "没有查找到满足条件的数据",
        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
        "sLengthMenu": "每页显示 _MENU_ 条记录",
        "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
        "oPaginate": {
          "sFirst": "首页",
          "sPrevious": "前一页",
          "sNext": "后一页",
          "sLast": "尾页"
        }
      },
    });
  },
  initQuery: function(){
    // status 和 rate两个字段是实时刷新的
    // dataTable摧毁和tableList赋值都砸在promise里完成
    // tableList只初始化的时候赋值一次 然后就不动了 用原生js去改变表格内的status字段
    let mySelf = this;
    let callback = function(){
      if($(&#39;#main-table&#39;).DataTable()){
        $(&#39;#main-table&#39;).DataTable().destroy()
      }
      mySelf.tableList = util.deepClone(mySelf.originTableList);
    }
    let queryTablePromise = mySelf.queryTable(callback);
    let promiseList = [];
    mySelf.clearRefresh();
    promiseList.push(queryTablePromise);
    Promise.all(promiseList).then(function (result) {
      console.log(&#39;ajax全部执行完毕:&#39; + JSON.stringify(result)); // ["Hello", "World"]
      //renderTable函数只在首次进入页面时调用 1.毁掉dataTable插件 2.加载一次表格更新状态和完成率 3.调用自动刷新
      mySelf.renderTable();
      mySelf.updateRefreshStatus();
      mySelf.setRefresh();
    });
  },
  switchRefreshStatus: function(){
    let mySelf = this;
    let status = mySelf.refresh.status;
    let text = (status==true)?&#39;关闭&#39;:&#39;开启&#39;;
    let confirmCallback = null;
    if (status==true){
      confirmCallback = function(){
        mySelf.refresh.status = false;
      }
    }
    else{
      confirmCallback = function(){
        mySelf.refresh.status = true;
        mySelf.setRefresh();
      }
    }
    util.showConfirm(&#39;确认要&#39; + text + &#39;自动刷新么?&#39;,confirmCallback);
  },
  checkTaskRefresh: function(){
    let mySelf = this;
    let originTableList = mySelf.originTableList;
    let taskAllComplete = true;
    // console.log(JSON.stringify(mySelf.originTableList));
    originTableList.forEach(function(item,index,array){
      let completeTaskList = mySelf.refresh.completeTaskList;
      let completeRate = item.completeRate;
      //当前task完成 report给后端
      if (Number.parseInt(completeRate) == 1){
        // 若任务完成列表 没有这个TaskId 则发送请求
        if (!completeTaskList.includes(item.id)){
          console.log(item.id + "任务完成了!并且不存在于任务完成列表,现在发送完成请求!");
          mySelf.reportTaskComplete(item.id);
          mySelf.refresh.completeTaskList.push(item.id);
        }
      }
      else{
        taskAllComplete = false;
      }
    });
    if(taskAllComplete){
      console.log(&#39;全部任务都完成了!&#39;)
      return true;
    }
    return false;
  },
  setRefresh: function(){
    let mySelf = this;
    let status = mySelf.refresh.status;
    let interval = mySelf.refresh.interval;
    // 如果所有任务都完成了 则停止发送ajax请求 并更新最后一次
    if (mySelf.checkTaskRefresh()){
      console.log(&#39;更新最后一次表格!&#39;)
      mySelf.updateRefreshStatus();
      return false;
    }
    // console.log(&#39;refresh&#39;)
    if (status){
      mySelf.refresh.timer = setTimeout(function(){
        let queryTablePromise = mySelf.queryTable();
        let promiseList = [];
        promiseList.push(queryTablePromise);
        Promise.all(promiseList).then(function (result) {
          console.log(&#39;ajax全部执行完毕:&#39; + JSON.stringify(result)); // ["Hello", "World"]
          mySelf.updateRefreshStatus();
          mySelf.setRefresh();
        });
      },interval);
    }
    else{
      mySelf.clearRefresh();
    }
  },
  updateRefreshStatus: function(){
    console.log(&#39;更新刷新状态&#39;)
    let mySelf = this;
    let mainTable = document.getElementById("main-table");
    let originTableList = mySelf.originTableList;
    originTableList.forEach(function(item,index,array){
      let trClassName = "id-" + item.id;
      // console.log(trClassName)
      // 获取当前页面展示的所有tr
      let trDom = mainTable.getElementsByClassName(trClassName)[0];
      // console.log(trDom)
      // 局部刷新个别字段
      if (trDom){
        let tdRate = trDom.getElementsByClassName("rate")[0];
        let tdStatus = trDom.getElementsByClassName("status")[0];
        tdRate.innerText = item.completeRate;
        tdRate.className = (item.status == "1")?"text-info rate":((item.status == "2")?"text-success rate":"text-danger rate");
        tdStatus.innerText = (item.status == "1")?"刷新中":((item.status == "2")?"刷新完成":"刷新失败");
        tdStatus.className = (item.status == "1")?"text-info status":((item.status == "2")?"text-success status":"text-danger status");
      }
    });
  },
  clearRefresh: function(){
    let mySelf = this;
    console.log(&#39;clear timer&#39;);
    clearTimeout(mySelf.refresh.timer);
  },
  queryTable: function(callback){
    let mySelf = this;
    let promise = new Promise(function (resolve, reject) {
      let url = pars.domain + "/api.php?Action=xxxxxxx&t=" + (new Date).getTime();
      $.get(url, function(res) {
        if (res.code == 0) {
          let resData = res.list;
          resData.forEach(function(item,index,array){
            let info = item.info;
            let completeCount = info.completeCount;
            let total = info.count;
            item.completeRate = ((completeCount/total)*100).toFixed(2) + "%";
          });
          // console.log(JSON.stringify(resData))
          mySelf.originTableList = resData;
          if (callback){
            callback();
          }
          resolve(&#39;queryTable完成!&#39;);
        }
        else{
          util.showDialog(&#39;error&#39;,"接口调用失败,报错信息为:" + res.message);
        }
      }, "json");
    });
    return promise;
  },
  renderTable: function(){
    let mySelf = this;
    mySelf.$nextTick(function(){
      mySelf.initRecordTable();
      util.hideLoading();
    })
  }
},
beforeRouteLeave (to, from, next){
  let mySelf = this;
  mySelf.clearRefresh();
  next();
},
Copy after login


The overall effect is as follows. The overall function is implemented, but it feels so stupid. If you have a good idea, please tell me! !

How to dynamically refresh tables using vue2.0 combined with the DataTable plug-in

The above is the detailed content of How to dynamically refresh tables using vue2.0 combined with the DataTable plug-in. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template