Skip to content

Instantly share code, notes, and snippets.

@yajra
Last active July 25, 2023 11:06
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save yajra/ff9218f58fc2d1499e7ce3d356549d24 to your computer and use it in GitHub Desktop.
Save yajra/ff9218f58fc2d1499e7ce3d356549d24 to your computer and use it in GitHub Desktop.
VueJS DataTables Snippets with Delete Button Component
require('./bootstrap');
window.Vue = require('vue');
Vue.component('data-table', require('./components/DataTable.vue'));
const app = new Vue({
el: '#app',
data() {
return {
columns: [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'created_at'},
{
data: 'action',
orderable: false,
searchable: false,
createdCell(cell, cellData, rowData) {
let DeleteButton = Vue.extend(require('./components/DeleteButton'));
let instance = new DeleteButton({
propsData: rowData
});
instance.$mount();
$(cell).empty().append(instance.$el);
}
},
]
}
}
});
<template>
<table>
<thead>
<tr>
<th v-for="column in parameters.columns" v-html="title(column)"></th>
</tr>
</thead>
<tfoot v-if="footer">
<tr>
<th v-for="column in parameters.columns" v-html="column.footer"></th>
</tr>
</tfoot>
</table>
</template>
<script>
window.$ = window.jQuery = require('jquery');
require('datatables.net');
require('datatables.net-bs');
require('datatables.net-buttons');
require('datatables.net-buttons-bs');
export default{
data() {
return {
dataTable: {},
}
},
methods: {
title(column) {
return column.title || this.titleCase(column.data);
},
titleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
},
computed: {
parameters() {
const vm = this;
return window.$.extend({
serverSide: true,
processing: true
}, {
ajax: this.ajax,
columns: this.columns,
createdRow(...args) {
vm.$emit('created-row', ...args);
},
drawCallback(...args) {
vm.$emit('draw', ...args);
},
footerCallback(...args) {
vm.$emit('footer', ...args);
},
formatNumber(...args) {
vm.$emit('format', ...args);
},
headerCallback(...args) {
vm.$emit('header', ...args);
},
infoCallback(...args) {
vm.$emit('info', ...args);
},
initComplete(...args) {
vm.$emit('init', ...args);
},
preDrawCallback(...args) {
vm.$emit('pre-draw', ...args);
},
rowCallback(...args) {
vm.$emit('draw-row', ...args);
},
stateLoadCallback(...args) {
vm.$emit('state-load', ...args);
},
stateLoaded(...args) {
vm.$emit('state-loaded', ...args);
},
stateLoadParams(...args) {
vm.$emit('state-load-params', ...args);
},
stateSaveCallback(...args) {
vm.$emit('state-save', ...args);
},
stateSaveParams(...args) {
vm.$emit('state-save-params', ...args);
},
}, this.options);
}
},
props: {
footer: { default: false },
columns: { type: Array },
ajax: { default: '' },
options: { }
},
mounted() {
this.dataTable = window.$(this.$el).DataTable(this.parameters);
},
destroyed() {
this.dataTable.destroy();
}
}
</script>
<template>
<button @click="deleteUser">
<slot>Delete</slot>
</button>
</template>
<script>
export default{
props: ['id', 'name'],
methods: {
deleteUser() {
alert(`I am ${this.name}!`)
}
},
}
</script>
@section('contents')
<data-table :columns="columns" class="table"></data-table>
@endsection
@antoniodesa
Copy link

Hi yajra,
This is almost perfect but how how can i make @click="" work on from ajax data?
Also the links from ajax data aren't working in VueRouter history mode. Any idea on how to get this to work on vue?

@yajra
Copy link
Author

yajra commented Oct 17, 2018

@antoniodesa you can use the draw callback and then attach the click handler.

    <data-table :columns="columns" class="table" @draw="draw"></data-table>

    // methods ...
    methods: {
        draw() {
            $('.btn-delete').on('click', function() {
                alert('delete')
            })
        }
    }

I may not be able to help you on VueRouter as I haven't use it yet.

@paragchirde
Copy link

paragchirde commented Sep 13, 2019

deleteUser(id){
                if(confirm("Are you sure you want to delete?")){
                    fetch(`api/article/${id}`,{
                        method:'delete'
                    })
                    .then(res => res.json())
                    .then(data => {
                        console.log('Deleted Article' + id);
                        //  dt.row($(this).parents('tr')).remove().draw(true);
                    })
                    .catch(err => console.log(err));
                }
           }

Now that I have deleted the row, I want that row to get removed instantaneously. But now I have to reload the page. how to redraw the table as soon as the post is deleted?

@irwaank
Copy link

irwaank commented Sep 5, 2021

Hi, I am a newbie and trying to implement this.

Could someone help me to direct me to full implementations detail / guidance ?

Thanks

@nardofransiscopurba
Copy link

nardofransiscopurba commented Oct 19, 2021

can you help me? how to use $emit('info') in component, can you give just 1 example?
infoCallback(...args) {
vm.$emit('info', ...args);
},

@zuhair2025
Copy link

zuhair2025 commented Mar 20, 2022

<router-link to="/amenities/edit/'.$row->id.'" class="edit btn btn-info btn-sm" type="button">EDIT</router-link></div>';

N:B: here <router-link></router-link> is not working on datatable. Please help me out.

@bkens
Copy link

bkens commented Feb 6, 2023

Hi yajra, This is almost perfect but how how can i make @click="" work on from ajax data? Also the links from ajax data aren't working in VueRouter history mode. Any idea on how to get this to work on vue?

Hello @antoniodesa, Did u get the answer for this question?

@yajra
Copy link
Author

yajra commented Feb 6, 2023

There is already official support for vue3. I suggest everyone use that instead. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment