问题包括在Vue.js中与Tabulator一起使用的Moment.js库



我正在尝试使用Tabulator的日期-时间功能,该功能需要moment.js库。在添加Tabulator之前,在我的应用程序中,moment.js已经在该级别的某些组件中使用。我有一个新的测试组件,它使用Tabulator并尝试使用datetime。通常,我只会导入矩并在这里使用它,但似乎矩是Tabulator本身所必需的。

我的第一个想法是Moment.js需要在我的应用程序中全局设置,所以我做到了。

Main.js:

```
import Vue from 'vue'
import App from './App'
import router from './router'
import { store } from './store'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import moment from 'moment'
Vue.prototype.moment = moment
...............
new Vue({
el: '#app',
data () {
return {
info: null,
loading: true,
errored: false // this.$root.$data.errored
}
},
router,
components: { App },
template: '<App/>',
store
})
```

在我的组件(Testpage.vue)

```
<template>
<div>
<div ref="example_table"></div>
</div>
</template>
<script>
// import moment from 'moment'
var Tabulator = require('tabulator-tables')
export default {
name: 'Test',
data: function () {
return {
tabulator: null, // variable to hold your table
tableData: [{id: 1, date: '2019-01-10'}] // data for table to display
}
},
watch: {
// update table if data changes
tableData: {
handler: function (newData) {
this.tabulator.replaceData(newData)
},
deep: true
}
},
mounted () {
// instantiate Tabulator when element is mounted
this.tabulator = new Tabulator(this.$refs.example_table, {
data: this.tableData, // link data to table
columns: [
{title: 'Date', field: 'date', formatter: 'datetime', formatterParams: {inputFormat: 'YYYY-MM-DD', outputFormat: 'DD/MM/YY', invalidPlaceholder: '(invalid date)'}}
],
}
</script>
```

我收到错误:"未捕获(承诺中)引用错误:未在Format.datetime中定义时刻(tabulator.js?ab1f:14619)"通过使用这个,我可以在其他组件中使用力矩$moment(),但我需要它在node_modules\tableratables\dist\js\tablerator.js中可用因为这就是错误发生的地方。知道怎么把图书馆包括在内吗?

回到您尝试的第一个选项,因为用moment注释Vue原型肯定不是正确的方法。即使它是推荐的(事实并非如此),Tabulator也必须知道如何通过查找Vue.moment来找到它。它并没有为此进行编码。

我喜欢开源的一点是,你可以准确地看到库在做什么来帮助解决这个问题。快速搜索Tabulator代码库可以发现:

https://github.com/olifolkerd/tabulator/blob/3aa6f17b04cccdd36a334768635a60770aa10e38/src/js/modules/format.js

var newDatetime = moment(value, inputFormat);

格式化程序只是直接调用moment,而不导入它。它显然是围绕着期望库在全球可用的老式机制设计的。在浏览器中,这意味着它在"窗口"对象上。有两个快速选项可以解决这个问题:

  1. 使用CDN托管的Moment版本,例如https://cdnjs.com/libraries/moment.js/把这样的东西放在你的页面模板的标题中:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
    
  2. 调整上面的代码以设置窗口上的时刻:

    window.moment = moment;
    

ohgodh为什么上面的评论从日期在很多方面都更好的角度来看并不一定是错误的。但它不适用于您,因为表格是硬编码的,以寻找时刻,所以您需要时刻本身来工作。

最新更新