这符合您的最低可行解决方案。
在您的列定义中:
render: function(data, type, row, meta) {
return `<span class="edit-placeholder">Edit</span>`
}
在您的 DataTable 组件中:
methods:{
editProperty(data){
console.log(data)
}
},
mounted: function() {
const table = $(this.$refs.table).dataTable({
ajax: this.url,
columns: this.columns
});
const self = this
$('tbody', this.$refs.table).on( 'click', '.edit-placeholder', function(){
const cell = table.api().cell( $(this).closest("td") );
self.editProperty(cell.data())
});
}
Example https://codepen.io/Kradek/pen/VbPZYq?editors=1010(使用不同的API,但想法相同)。
这是使用 jQuery,但您已经在使用 jQuery,所以感觉并没有那么糟糕。
我玩了一些游戏试图将组件安装在render
数据表的功能取得了一些成功,但我对 DataTable API 还不够熟悉,无法使其完全工作。最大的问题是 DataTable API 期望渲染函数返回一个字符串,这是......限制。该 API 还非常令人恼火不会为您提供对当前所在单元格的引用,这似乎是显而易见的。否则你可以做类似的事情
render(columnData){
const container = document.createElement("div")
new EditComponent({data: {columnData}).$mount(container)
return container
}
此外,渲染函数以多种模式调用。我能够将组件渲染到单元中,但必须使用模式等玩很多游戏。这是一次尝试 https://codepen.io/Kradek/pen/BRpNLN?editors=1010,但它有几个问题。我将其链接起来是为了让您了解我在尝试什么。也许你会取得更大的成功。
最后,你can将组件安装到 DataTable 呈现的占位符上。考虑这个组件。
const Edit = Vue.extend({
template: `<a @click='editProperty' class='btn btn-warning'><i class='fa fa-pencil'></i> Edit</a>`,
methods:{
editProperty(){
console.log(this.data.name)
this.$emit("edit-property")
}
}
});
在您安装的方法中,您可以这样做:
mounted: function() {
const table = $(this.$refs.table).dataTable({
ajax: this.url,
columns: this.columns
});
table.on("draw.dt", function(){
$(".edit-placeholder").each(function(i, el){
const data = table.api().cell( $(this).closest("td") ).data();
new Edit({data:{data}}).$mount(el)
})
})
}
这将在每个占位符顶部渲染一个 Vue,并在绘制时重新渲染它。Here https://codepen.io/Kradek/pen/BRpNPL?editors=1010就是一个例子。