Moment.js with Vuejs
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>
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>