DEV Community

Febriansyah
Febriansyah

Posted on • Updated on

How to add jQuery DataTables to NuxtJS 2

Hello everyone... this is first my article in dev.to
Today i'm share to you about How to add jQuery DataTables to NuxtJS 2. and here I use the css framework from bootstrap with version 5.1.x

I assume that you guys have installed NuxtJS. So now straight to the point.


  1. Install jQuery and DataTables
    If you use other than bootstrap, you can use something else like bulma etc. For example

    npm install jquery datatables.net-bs5
    

    or

    yarn add jquery datatables.net-bs5
    
  2. Install types for jQuery and DataTables

    npm install @types/jquery @types/datatables.net --dev
    

    or

    yarn add @types/jquery @types/datatables.net --dev
    
  3. Add types to tsconfig.json

    "types": [
      ...
      "@types/jquery",
      "@types/datatables.net"
      ...
    ]
    
  4. Create a JavaScript with name scripts.js in assets/js/scripts.js then add the code below

    import 'bootstrap'
    import 'datatables.net-bs5'
    
  5. Open file nuxt.config.js
    In the first line add the code below

    import { ProvidePlugin } from 'webpack'
    

    Scroll down then we will find the Plugins. then add the code below

    // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
    plugins: [
    ...
    {
      src: '~/assets/js/scripts.js',
      mode: 'client'
    }
    ...
    ],
    

    Scroll down then we will find the Build Configuration. then add the code below

    // Build Configuration: https://go.nuxtjs.dev/config-build
    build: {
    ...
    plugins: [
      new ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
      })
    ]
    ...
    }
    
  6. Let's create a new file in the pages folder. I'll name it datatables.vue
    then add the code below and save it in the html script tag

    export  default  Vue.extend({
        name: 'DataTablesPage',
        mounted () {
            $('#datatables').DataTable()
        }
        ...
    })
    
  7. Now, run this

    npm run dev
    

    or

    yarn dev
    

Now, you can see the result.
Like this

Image description

or, you can also add a language. For example using Indonesian. For a list of languages ​​you can see here.

$('#datatables').DataTable({
   language: {
     url: 'https://cdn.datatables.net/plug-ins/1.12.1/i18n/id.json'
   }
})
Enter fullscreen mode Exit fullscreen mode

Image description

For source code: https://github.com/febryars33/nuxtjs-datatables-example

Top comments (0)