search
HomeWeb Front-endJS TutorialHow to dynamically refresh tables using vue2.0 combined with the DataTable plug-in

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 id="点播刷新任务数据表格-nbsp-nbsp-small-Secondary-nbsp-text-small-nbsp">点播刷新任务数据表格 <!-- <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>


##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();
},


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!

Statement
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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment