0

I am using datatable jQuery plugin with vueJs but I encounter a problem when I use the render function of the datatable. If I put vueJs code inside, like @click, it is not interpreted, and I see in the source code @click and nothing is happening.

I create a component Datatable and I instantiate like this

<Datatable v-if="!loading" :source="source" :columns="columns" :searching="searching"></Datatable>

source is an array like this

[["1","138","415-CS-92","8","1"],["1","138","415-CS-92","8","1"]]

and columns is an array like this

[
      { title: "foo" },
      { title: "foo2" },
      { title: "foo3" },
      { title: "foo4" },
      { title: "foo5" ,
        render: function(data, type, row, meta) {
          return '<a @click="test">' + data +' <i class="fa fa-edit "></i></a>';
        }
      }
    ]

The problem is exactly there, the render function returns the @click directive without compiling it

Template of Datatable component

<template>
 <div>
   <table class="display" style="width:100%">
   </table>
 </div>
</template>

script:

  export default {
  props: ['source', 'columns', 'searching'],
  data () {
    return {
      datatable: {}
    }
  },
  mounted: function () {
    var the = this
    the.$nextTick(function () {
      this.datatable = $($(this.$el).find('table')).DataTable({
        data: the.source,
        columns: the.columns,
        searching: the.searching
      });
    })
  },
  watch: {
    'source': {
      handler: function(val, oldVal) {
        var the = this
        the.$nextTick(function () {
          this.datatable.destroy()
          this.datatable = $($(this.$el).find('table')).DataTable({
            data: the.source,
            columns: the.columns,
            searching: the.searching
          });
        })
      },
      deep: true
    }
  }
}

Thanks in advance

Jonathan COHEN
  • 125
  • 1
  • 2
  • 8

1 Answers1

0

jQuery DataTables is not a Vue native component; therefore, it's not reactive. This mean you cannot wire '@click' event as shown in your code. (Unless you're doing it in created phase which is probably what cause this issue where you can't rewire the event in later phases.)

(Shameless Plug) check out my example Vue component on how to handle click with data-action attribute: https://github.com/niiknow/vue-datatables-net

It use jQuery to handle click, then propagate/$emit the event (name defined as data-action attribute) to the Vue component.

Noogen
  • 1,652
  • 12
  • 13