首页 > 解决方案 > How do I call a Vue.js method from a link inside data table?

问题描述

I am building a Vue.js application using the Vue Webpack template. Within a component, I am initializing a Datatable like this:

<script>
export default {
  name: 'DataTable',

  mounted() {
    $('#datatable').dataTable({
      serverSide: true,
      ajax: {
        url: '/tableData',
      },
      processing: true,
      searching: false,
      pageLength: 25,
      order: [[0, 'desc']],
      columns: [
        {
          searchable: false,
          data: 'updatedAt',
          render: data => format(new Date(data), 'MMM Do, YYYY - h:mm:ss a'),
        },
        {
          orderable: false,
          data: 'user',
          render: (data) => {
            return `${data.firstName} ${data.lastName}`;
          },
        },
        {
          searchable: false,
          orderable: false,
          render() {
            return '<a href="javascript:void" @click="openModal">View Details</a>';
          },
        },
      ],
    });
  },

  methods: {
    openModal() {
      console.log('Open modal code goes here');
    }
  }
}
</script>

This works fine and the table is rendered in the browser. My question - how do I call the openModal() method from inside the data table? As you can see, I am trying to call the method in columns[2].render but that doesn't work (likely because Vue does not compile the return string. How can I make this work?

标签: javascriptvue.jsdatatable

解决方案


您可以在数据表回调上添加点击事件。希望这可以帮助

      mounted() {
               var self = this;
                $('#datatable').dataTable({
                    serverSide: true,
                    ajax: {
                        url: '/tableData',
                    },
                    processing: true,
                    searching: false,
                    pageLength: 25,
                    order: [[0, 'desc']],
                    columns: [
                        {
                            .........
                        },
                        { title: 'Action', targets:7, data: 'id',
                            "render":function(data, type, row, meta){
                                //data item in case you want to send any data
                                return '<a  href="javascript:void" data-item-id='+data+' class="open-item">Open Modal</a>';
                            }
                        }
                    ],
                    "drawCallback": function( settings ) {
                        $(".open-item").on( 'click', function (e) {
                            self.OpenModal(e.target.dataset.itemId);
                        });
                    }
                });
            },
            methods: {
                openModal:function() {
                    console.log('Open modal code goes here');
                }
            }

推荐阅读