javascript-使用VueJS动态编译和挂载元素
作者:互联网
问题
我为VueJS围绕jQuery数据表创建了一个轻量级包装,如下所示:
<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>
请注意“操作”列的“渲染”方法.此函数运行正常,并按预期方式呈现按钮,但是@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上下文外部调用方法?
解决方法:
这符合您的最小可行解决方案.
在您的列定义中:
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,因此感觉并不那么糟糕.
我玩了一些游戏,试图成功地将组件安装到数据表的呈现功能中,但是我对DataTable API不够熟悉,无法使其完全正常工作.最大的问题是DataTable API希望render函数返回一个字符串,这是有限制的.该API也很烦人,没有提供您当前所在单元格的引用,这很明显.否则你可以做类似的事情
render(columnData){
const container = document.createElement("div")
new EditComponent({data: {columnData}).$mount(container)
return container
}
同样,render函数以多种模式调用.我能够将一个组件渲染到单元中,但是不得不使用模式等进行很多游戏.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.
标签:vue-js,datatables,vuejs2,javascript,jquery 来源: https://codeday.me/bug/20191111/2019879.html