1

I would like to implement DataTables with my Vue3 application. But have a problem with correct import.

Import according documentation does not work.

var $  = require( 'jquery' );
var dt = require( 'datatables.net' )();

Throws: Cannot set property '$' of undefined

So I tried everything I found but without success. I have a github project with example branch datatables. The code with imports is in main.js file.

Now I have this import

import jQuery from 'jquery/src/jquery.js'
window.$ = window.jQuery = jQuery;
import dataTables from 'datatables.net';
window.dt = dataTables;

Throws: $(...).DataTable is not a function.

I am lost in it. What happened under the DataTables hood why it is not possible to join it with jQuery?

Thanks for any help.

1 Answer 1

1

At first step install via NPM jQuery and datatables:

  • npm install jquery
  • npm install datatables.net

Then import in script tag in component or view:

import $ from "jquery";
import DataTable from "datatables.net";

But if you need to globally import jQuery and DataTable, you can import this (as you wrote) in main.js:

window.$ = window.jQuery = require('jquery');
import {DataTable} from "datatables.net";

Then pass your table (here table has name "testTable") to DataTable function:

export default {
  data() {
    return {
      testTable: [
        [
          "Tiger Nixon",
          "System Architect",
          "Edinburgh",
          "5421",
          "2011/04/25",
          "$3,120"
        ],
        [
          "Tiger Nixon",
          "System Architect",
          "Edinburgh",
          "5421",
          "2011/04/25",
          "$3,120"
        ]
      ]
    };
  },
  mounted() {
    $("#example").DataTable({
      data: this.testTable
    });
  }

And output it in template by table tag:

<table id="example">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Extn.</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
</table>

I hope I helped.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I have it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.