Moment.js with Vuejs - momentjs

I try to print out date time using like the following in vue-for
{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}
but, it does not appear. It's just a blank. How I can try to use moment in vue?

With your code, the vue.js is trying to access the moment() method from its scope.
Hence you should use a method like this:
methods: {
moment: function () {
return moment();
}
},
If you want to pass a date to the moment.js, I suggest to use filters:
filters: {
moment: function (date) {
return moment(date).format('MMMM Do YYYY, h:mm:ss a');
}
}
<span>{{ date | moment }}</span>
[demo]

If your project is a single page application, (eg project created by vue init webpack myproject),
I found this way is most intuitive and simple:
In main.js
import moment from 'moment'
Vue.prototype.moment = moment
Then in your template, simply use
<span>{{moment(date).format('YYYY-MM-DD')}}</span>

In your package.json in the "dependencies" section add moment:
"dependencies": {
"moment": "^2.15.2",
...
}
In the component where you would like to use moment, import it:
<script>
import moment from 'moment'
...
And in the same component add a computed property:
computed: {
timestamp: function () {
return moment(this.<model>.attributes['created-at']).format('YYYY-MM-DD [at] hh:mm')
}
}
And then in the template of this component:
<p>{{ timestamp }}</p>

I made it work with Vue 2.0 in single file component.
npm install moment in folder where you have vue installed
<template>
<div v-for="meta in order.meta">
{{ getHumanDate(meta.value.date) }}
</div>
</template>
<script>
import moment from 'moment';
export default {
methods: {
getHumanDate : function (date) {
return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY');
}
}
}
</script>

Here is an example using a 3rd party wrapper library for Vue called vue-moment.
In addition to binding Moment instance into Vue's root scope, this library includes moment and duration filters.
This example includes localization and is using ES6 module imports, an official standard, instead of NodeJS's CommonJS module system requires.
import Vue from 'vue';
import moment from 'moment';
import VueMoment from 'vue-moment';
// Load Locales ('en' comes loaded by default)
require('moment/locale/es');
// Choose Locale
moment.locale('es');
Vue.use(VueMoment, { moment });
Now you can use the Moment instance directly in your Vue templates without any additional markup:
<small>Copyright {{ $moment().year() }}</small>
Or the filters:
<span>{{ 3600000 | duration('humanize') }}</span>
<!-- "an hour" -->
<span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span>
<!-- "3 years" -->

// plugins/moment.js
import moment from 'moment';
moment.locale('ru');
export default function install (Vue) {
Object.defineProperties(Vue.prototype, {
$moment: {
get () {
return moment;
}
}
})
}
// main.js
import moment from './plugins/moment.js';
Vue.use(moment);
// use this.$moment in your components

For moment.js at Vue 3
npm install moment --save
Then in any component
import moment from 'moment'
...
export default {
created: function () {
this.moment = moment;
},
...
<div class="comment-line">
{{moment(new Date()).format('DD.MM.YYYY [ ] HH:mm')}}
</div>

Moment.js with Vue3 js
npm install moment --save # npm
yarn add moment # yarn
Main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import moment from 'moment'
const app = createApp(App)
app.config.globalProperties.$moment = moment
app.use(router).mount('#app')
Used moments in vue3 js component
{{ $moment(item.created_at).format("YYYY-MM-DD") }} // 2021-07-03

global members are not available by default in your <template>'s scope. But you can easily pass them on using computed properties.
computed: {
moment: () => moment,
console: () => console,
window: () => window
}
Now you can use any of them in your template. i.e: console.log(moment(), window).
Note this doesn't add any overhead.

vue-moment
very nice plugin for vue project and works very smoothly with the components and existing code.
Enjoy the moments...😍
// in your main.js
Vue.use(require('vue-moment'));
// and use in component
{{'2019-10-03 14:02:22' | moment("calendar")}}
// or like this
{{created_at | moment("calendar")}}

I've read the solutions posted here and it seems to be more complex than my solution so I'm presenting this one, what I do is like this
The thing you need:
import moment from 'moment';
...
data() {
return {
moment: moment, // This is the one line of code that you need
}
}
So this is what it looks like
HTML (Now this works):
<h1>{{moment().format('MMMM Do YYYY, h:mm:ss a')}}</h1>
JS:
import moment from 'moment';
export default {
data() {
return {
moment: moment, // This is the one line of code that you need
}
}
}

I'd simply import the moment module, then use a computed function to handle my moment() logic and return a value that's referenced in the template.
While I have not used this and thus can not speak on it's effectiveness, I did find https://github.com/brockpetrie/vue-moment for an alternate consideration

TESTED
import Vue from 'vue'
Vue.filter('formatYear', (value) => {
if (!value) return ''
return moment(value).format('YYYY')
})

Install the moment module:
npm i moment
In your vue component:
import moment from 'moment';
export default {
data(){
},
methods:{
moment(date){ return moment(date) }
}
}
Inside the template:
<span>{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}</span>

Related

Vue3 script setup without all the imports from vue

I find it very repetitive to have to import vue things like:
import { ref, computed } from 'vue'
In the script setup section.
Would it be a bad practice to, let's say assign vue to a special character, like $ and then use it to access these like
let drawer = $.ref(null);
If so what would be the reasoning behind?
You can use the experimental version of vue3:
// vite.config.js
export default {
plugins: [
vue({
reactivityTransform: true
})
]
}
after that there is an auto import available and you don't have to write .value if using a $ref or $computed.
Because $ref() is a macro and not a runtime API, it doesn't need to be imported from vue.

Problem creating a WebComponent from a SFC with Vue 3.2.9

I am trying to create a web component in Vue3. For this I use the Vue cli with the target library. Everything works as expected.
The problem is that I can't get any values from the props parameter of the setup function.
If I use the component as a Vue component the props work. As a web component i cant get any value from the props parameter
Its seams that the property wc-Test is not forwarded properly.
Does anyone have any ideas?
The Component Code
<template>
<a class="btn">
<slot></slot>
</a>
</template>
<script>
import {version } from "vue";
export default {
name: 'xn-button',
props: {
variant: {
default: 'normal',
type: String
}
},
setup(props, context) {
console.log(`Vue: ${version}`)
console.log(props)
console.log(props.variant)
},
}
</script>
<style></style>
Usage as Part of Vue Library:
<xn-button variant="Vue-Test">Test1</xn-button>
Usage as WebComponent:
<xn-button variant="wc-Test">Test2</xn-button>
Console output:
image

Why is my vuejs dependency maz-ui maz-phone-number-input not formatted properly?

I am using the https://louismazel.github.io/maz-ui/ library to include a country code dropdown in the phone number input field of my sign up form. Here is documentation for this particular component from the library.
https://louismazel.github.io/maz-ui/documentation/maz-phone-number-input/
Why is my phone number field formatted like this?
rather than the expected appearance from the Maz-ui docs? ...
Here the relevant code in my component...
<template>
<div>
<MazPhoneNumberInput
v-model="phoneNumber"
/>
... more code that is not directly relevant to this question.
</div>
</template>
<script>
import { MazPhoneNumberInput } from 'maz-ui'
import 'maz-ui/lib/css/maz-phone-number-input.css'
export default {
name: 'CuiRegister',
components: { MazPhoneNumberInput },
}
... code for handling the form submission that is not directly related to this question
</script>
This is happening because it is not importing the css properly.
So if you import the component and its CSS properly it should work:
import MazPhoneNumberInput from "maz-ui/lib/maz-phone-number-input";
import "maz-ui/lib/css/base.css";
import "maz-ui/lib/css/maz-phone-number-input.css";
Or
add this code to your babel.config.js file:
module.exports = {
plugins: [
[
'component',
{
libraryName: 'maz-ui',
styleLibraryName: 'css'
}
]
]
};
I got the second solution from the documentation here

How can I use single file vue component with symfony 4?

What I want to do is:
1) in app.js to be able to use
import Vue from 'vue'
import Time from './vue/components/Time'
Vue.component('vue-time', {
template: '<span class="foo bar">Hi</span>'
})
new Vue({
el: 'header',
components: { Time }
})
2) in Time.vue:
<template>
<div>current time</div>
</template>
<script>
module.exports = {
}
</script>
<style>
</style>
Is this possible? All is implemented using encore-webpack and symfony4.
Thanks.
in app.js registered 2 components:
Time - registered localy
vue-time - registered global
if you want register Time global add in app.js this:
*do not use name Time https://developer.mozilla.org/uk/docs/Web/HTML/Element/time
Vue.component(`Time`, Time)
in app.js delete this:
components: { Time }
then use tag <time></time> anywhere in your application

what is the proper way to use createContainer() in Meteor + Blaze + React?

i have a working component where i'm doing this:
import React, {Component, PropTypes} from 'react';
import {createContainer} from 'meteor/react-meteor-data';
export default class Foo extends Component {
}
export default createContainer(() => {
}, Foo);
import Foo from '/imports/ui/components/Foo';
i am using Blaze to wrap the React components, like this:
import Foo from '/imports/ui/components/Foo';
Template.registerHelper("Foo", function() {
return Foo;
);
<div>
{{> React component=Foo}}
</div>
i realize that i shouldn't be doing multiple default exports in a single file, but it does work. note that this is with these versions: Meteor v1.4.1.1, Meteor npm v3.10.6, Meteor node v4.5.0.
i now have a test harness, with Meteor v1.4.2.3, Meteor npm v3.10.9 and Meteor node v4.6.2, where this has stopped working. not surprisingly, in my server console:
While building for web.browser:
imports/ui/components/Foo.jsx:58: Only one default export allowed
per module. (58:0)
so now i'm looking for a way to get this back working, and in the proper way.
what i've tried:
first, keeping the component and the create container in the same file, i did proper ES6 exporting:
const Foo = class Foo extends Component {
const FooContainer = createContainer(() => {
export {Foo, FooContainer};
... and imported Foo.
result: Foo loaded in the app, but the container code never ran.
second, i put the component and the create container in two different files, and reverted to exporting defaults:
// Foo.jsx
export default class Foo extends Component {
// FooContainer.jsx
export default createContainer(() => {
... and used Foo:
import Foo from '/imports/ui/components/Foo';
Template.registerHelper("Foo", function() {
return Foo;
});
<div>
{{> React component=Foo}}
</div>
result: Foo loaded in the app, but the container code never ran.
third, similar to the above, but i instead tried putting FooContainer on the page:
import FooContainer from '/imports/ui/components/FooContainer';
Template.registerHelper("Foo", function() {
return FooContainer;
});
<div>
{{> React component=Foo}}
</div>
result: big error message from React that basically i wasn't doing it right.
any idea on the proper way to get this to work?
update:
attempts 4 and 5
put both back into same class, like this:
export class Foo extends Component {
export default createContainer(() => {
... with 2 different ways of importing it:
import Foo from '/imports/ui/components/Foo';
that ran createContainer() but did not put my component on the page.
import {Foo} from '/imports/ui/components/Foo';
that did the opposite: did not run createContainer(), but i did see the component.
got it working, in 1 jsx file:
export class Foo extends Component {
export default createContainer(() => {
in the helper, relying on the default export:
import Foo from '/imports/ui/components/Foo';
the actual problem was i had incorrectly imported a server file to publish, and that caused a chain reaction which caused the component to not render. doh.

Resources