为 Vue v3 导入 Vue-luxon - this.$luxon 不是函数错误



我已经尝试了我能想到的一切让 vue-luxon 在我的 Laravel 8/Vue 3 应用程序上工作,但失败了。我根据文档执行了以下步骤:

npm install vue-luxon;

文档没有说明在哪里,但我把这句话放在我的应用程序.js文件中:

import VueLuxon from "vue-luxon";

据我了解,这一行必须更改为 App.use(VueLuxon),并且也放置在 app.js:

Vue.use(VueLuxon);  

而且(根据文档),就是这样...我应该可以打电话:

this.$luxon("2020-10-05T14:48:00.000Z")

以显示格式化的日期,但我在控制台上不断收到此错误:

未捕获的类型错误:this.$luxon 不是一个函数

这是我的资源/js/app.js文件的内容:

import { createApp } from 'vue';
import App from './components/App.vue'
import VueLuxon from "vue-luxon";
createApp({
components: {
App,
}
}).mount("#app")
App.use(VueLuxon)

以及我的 js/components/App.vue 文件的内容:

<template>
<div class="flex flex--column flex--align-center flex--justify-center">
<div class="logos">
<img src="../../static/img/laravel.png" width="240" alt="" />
<img src="../../static/img/vue.png" width="240" alt="" />
</div>
<div class="title">
<h1 class="vue">Vue 3</h1>
<h1 class="plus">+</h1>
<h1 class="laravel">Laravel 8</h1>
</div>
{{ this.$luxon("2020-10-05T14:48:00.000Z") }}
</div>
</template>
<script>
// import VueLuxon from "vue-luxon"; // I´ve tried importing luxon here... doesn't work either.
export default {
mounted() {
console.log("Component mounted.");
},
};
</script>

我尝试将导入直接放在组件上,注册为应用程序组件或任何可能的组合,结果相同。我肯定错过了一些东西,所以任何帮助将不胜感激。

谢谢!

你可以在 vue 3 中使用 globalProperties:

在你的主.js

const { DateTime } = require("luxon");
app.config.globalProperties.$luxonDateTime = DateTime;

然后在模板中:

<template>
{{ $luxonDateTime.fromISO("2020-10-05T14:48:00.000Z").toRelative() }}
</template>

你会得到"6个月前">

首先,不要在模板中使用"this."。

根据官方存储库,该插件与 Vue 3 不兼容,仅与 Vue 2 兼容(至少目前如此)。

资料来源:https://github.com/casbloem/vue-luxon/issues/21

解决 方案:

  1. 等待更新。
  2. 分叉此存储库(并在之后发出拉取请求)。
  3. 由于它在引擎盖下使用 luxon 库,请为它编写自己的包装器。 https://github.com/moment/luxon
  4. 查找处理日期的替代方案。

对于 Vue3,你也可以尝试:

import { App } from 'vue';
import {
DateTime,
Duration,
Interval,
...
} from 'luxon'
type TLuxon = {
DateTime: typeof DateTime,
Duration: typeof Duration,
Interval: typeof Interval,
...
} 
const luxon: TLuxon = {
DateTime,
Duration,
Interval,
...
}
export default{
install:(app: App) => {
function load(): TLuxon{
return luxon
}
app.config.globalProperties.$lx = load();
}    
};
declare module "@vue/runtime-core" {
//Bind to `this` keyword
interface ComponentCustomProperties {
$lx: TLuxon;
}
}

然后在main.ts中:

import luxonLoader from './modules/luxon/luxonLoader'
createApp(App)
.use(store)
.use(router)
.use(luxonLoader)
.mount('#app')

您可以在任何模板中使用 luxon:

<template>
<div class="home">
{{time}}
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import HelloWorld from '@/components/HelloWorld.vue';
export default defineComponent({
name: 'HomeView',
components: {
HelloWorld,
},
computed: {
time(): string{
let currentTime = this.$luxeon.DateTime.now().toString()
return currentTime
}
}
});
</script>

最新更新