我为VueJS创建了一个围绕jQuery DataTables的轻量级包装器,如下所示:
<template>
<table ref="table" class="display table table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th v-for="(column, index) in columns">
{{ column.name }}
</th>
</tr>
</thead>
</table>
</template>
<script>
export default {
props: ['columns', 'url'],
mounted: function () {
$(this.$refs.table).dataTable({
ajax: this.url,
columns: this.columns
});
// Add any elements created by DataTable
this.$compile(this.$refs.table);
}
}
</script>
我正在使用数据表:
<data-table
:columns="
[
{
name: 'County',
data: 'location.county',
},
{
name: 'Acres',
data: 'details.lot_size',
},
{
name: 'Price',
data: 'details.price',
className: 'text-xs-right',
},
{
name: 'Actions',
data: null,
render: (row) => {
return "\
<a @click='editProperty' class='btn btn-warning'><i class='fa fa-pencil'></i> Edit</a>\
";
}
},
]
"
url="/api/properties"
></data-table>
请注意Actions列的“render”方法。此函数运行正常并按预期呈现按钮,但@click
处理程序不起作用。
环顾四周,我发现了两个没用的链接:
Issue 254 on the VueJS GitHub repo为VueJS 1.0提供了一个解决方案(使用this.$compile
),但这已在VueJS 2.0中删除
A blog post by Will Vincent讨论了当本地数据动态变化时如何重新渲染DataTable,但没有提供将处理程序附加到渲染元素的解决方案
如果无法编译和挂载渲染的元素,只要我可以单击运行DataTable
组件的方法,那就没问题。也许是这样的事情:
render: (row) => {
return "\
<a onclick='Vue.$refs.MyComponent.methods.whatever();' />\
";
}
有没有这样的方法从Vue上下文之外调用方法?
答案 0 :(得分:3)
这符合您最不可行的解决方案。
在您的列定义中:
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(使用不同的API,但想法相同)。
这是使用jQuery,但你已经在使用jQuery,所以它并不觉得那么糟糕。
我玩了一些游戏试图让一个组件安装在数据表的render
函数中取得了一些成功,但我对DataTable API不够熟悉,无法使其完全正常工作。最大的问题是DataTable API期望render函数返回一个字符串,这是...限制。 API也非常恼人没有为您提供您当前所在单元格的引用,这看起来很明显。否则你可以做类似
render(columnData){
const container = document.createElement("div")
new EditComponent({data: {columnData}).$mount(container)
return container
}
此外,使用多种模式调用渲染功能。我能够将一个组件渲染到单元格中,但是必须使用模式等来玩很多游戏This is an attempt,但它有几个问题。我将它链接起来让你知道我在尝试什么。也许你会有更多的成功。
最后,可以将组件装载到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就是一个例子。