【问题标题】:What is the correct way to load datatables.net plugin into a Vue Webpack app?将 datatables.net 插件加载到 Vue Webpack 应用程序的正确方法是什么?
【发布时间】:2018-10-21 20:04:37
【问题描述】:

我正在构建一个依赖于DataTables 的 Vue Webpack 应用程序。数据表插件依赖于 jQuery,据我了解,我无法将其导入到我的 Vue 组件中,例如 import datatable from 'datatables.net';

因此,这就是我当前导入它的方式:

<template>
  <table id="datatable" class="table"></table>
</template>

<script>
export default {
  name: 'MyComponent',

  beforeCreate() {
    // Fetch jQuery and Datatables JS
    const jQueryElem = document.createElement('script');
    jQueryElem.setAttribute('src', 'https://code.jquery.com/jquery-3.3.1.min.js');
    document.head.appendChild(jQueryElem);

    let dataTableIntervalCount = 0;
    const dataTableInterval = setInterval(() => {
      dataTableIntervalCount += 1;
      if (dataTableIntervalCount === 100) {
        clearInterval(dataTableInterval);
        this.dataTableError = true;
      }

      if (window.$) {
        // Load JS
        const dataTableElem = document.createElement('script');
        dataTableElem.setAttribute('src', 'https://cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.js');
        document.head.appendChild(dataTableElem);

        // Load CSS
        const dataTablesCss = document.createElement('link');
        dataTablesCss.setAttribute('rel', 'stylesheet');
        dataTablesCss.setAttribute('type', 'text/css');
        dataTablesCss.setAttribute('href', 'https://cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.css');
        document.head.appendChild(dataTablesCss);

        clearInterval(dataTableInterval);
      }
    }, 50);
  },
}
</script>

这让我很痛苦。我必须检查 jQuery 是否已加载,然后才从 CDN 插入数据表插件。否则,它会在控制台中引发错误。

获取数据表插件后,我现在必须在另一个 setInterval() 内的 #datatable 元素上对其进行初始化,因为从 CDN 获取插件需要几毫秒。这有时会导致另一个控制台错误,并且需要相当多的解决方法。

有没有更可靠的方法来做到这一点?谢谢。

【问题讨论】:

  • 也许你也可以分享你的 webpack 配置文件。如果您在其中自定义了 var $ = require("jquery"); 之类的行,这将特别有用。

标签: jquery vue.js datatables


【解决方案1】:

简单地说:

import jquery from 'jquery'

您实际上不必加载/打包 jQuery,您可以像这样将其 webpack 为外部:

externals: {
'jquery': 'jQuery',
'vue': 'Vue'
}

然后像往常一样在页面上加载 jQuery。这是关于 webpack 外部的文档:https://webpack.js.org/configuration/externals/

(无耻插件)我在这里为 Vue 创建了 jQuery DataTables 包装器:https://github.com/niiknow/vue-datatables-net#usage

有关如何加载所有内容的更多信息,请参阅用法和演示。

【讨论】:

    猜你喜欢
    • 2016-07-26
    • 2021-05-09
    • 1970-01-01
    • 2017-12-16
    • 2020-09-30
    • 2021-09-14
    • 1970-01-01
    • 2011-12-31
    • 2017-09-14
    相关资源
    最近更新 更多