在Vuejs中包含和使用moment的正确步骤是什么



我正试图在Vuejs应用程序中调用moment((,我试着这样声明它:

methods: {
moment: function () {
return moment();
}
},

并试着这样测试它:

beforeMount() {
console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
},

我一直收到

[Vue warn]:beforeMount挂钩中的错误:"ReferenceError:力矩未定义";

我需要在我的package.json中添加一些时间并运行yarn安装吗?

我想让它尽可能轻,因为我只需要访问应用程序的一个页面的moment((,我宁愿不在所有页面上加载它们。

请建议

首先应该使用以下命令进行安装:

npm i moment --save

然后在你的组件中导入它并像一样使用它


import moment from 'moment/moment';
export default{
...
beforeMount() {
console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
}
}

由于moment是一个不推荐使用的库(由于可变性(,在大小方面也是一个巨大的库,因此建议使用其他现代库sushdayjs,它只是一个2kB快速库,提供与moment 相同的功能

你可以安装

npm install dayjs --save

然后在你的项目中(使用特定的插件天js来显示你的特定格式Do(

import advancedFormat from 'dayjs/plugin/advancedFormat';
export default{
...
beforeMount() {
dayjs.extend(advancedFormat) // use plugin
console.log(dayjs().format('MMMM Do YYYY, h:mm:ss a'))
}

请参阅纯js:中的snnipet示例

dayjs.extend(dayjs_plugin_advancedFormat);
console.log(dayjs().format('MMMM Do YYYY, h:mm:ss a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/plugin/advancedFormat.min.js"></script>

相关内容

最新更新