Table of Contents
点播刷新任务数据表格 
Home Web Front-end JS Tutorial How to dynamically refresh tables using vue2.0 combined with the DataTable plug-in

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

Mar 19, 2017 am 09:54 AM

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>
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!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles