Čamo
Čamo

Reputation: 4160

$(...).DataTable is not a function in Vue3 application

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.

Upvotes: 1

Views: 1872

Answers (1)

Krystian Książek
Krystian Książek

Reputation: 126

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.

Upvotes: 1

Related Questions