- Vue.js 2 Web Development Projects
- Guillaume Chau
- 353字
- 2021-07-02 22:34:30
Created date with a filter
We will now display the creation date of the selected note in the status bar.
- In the status bar p element, create a new span element as follows:
<span class="date"> <span class="label">Created</span> <span class="value">{{ selectedNote.created }}</span> </span>
Now, if you look at the result displayed in your browser, you should see the number of milliseconds representing the date the note was created:

This is not user-friendly at all!
We need a new library to help us format the date into a more readable result--momentjs, which is a very popular time and date manipulation library.
- Include it in the page like we did for the marked library:
<script src="https://unpkg.com/moment"></script>
To format a date, we will first create a moment object, and then we will use the format method like in the following:
moment(time).format('DD/MM/YY, HH:mm')
Now is the time to introduce one last feature of Vue for this chapter--the filters. These are functions that are used inside templates to easily process data before it is displayed or passed to an attribute. For example, we could have an uppercase filter to transform a string into uppercase letters or a currency filter to convert currencies on the fly in a template. The function takes one argument--the value to be processed by the filter. It returns the processed value.
So, we will create a new date filter that will take a date time and will format it to a human-readable format.
- Register this filter with the Vue.filter global method (outside of the Vue instance creation code, for example, at the beginning of the file):
Vue.filter('date', time => moment(time)
.format('DD/MM/YY, HH:mm'))
Now, we can use this date filter in our template to display dates. The syntax is the JavaScript expression like we used before, followed by a pipe operator and the name of the filter:
{{ someDate | date }}
If someDate contains a date, it will output something like this in the DOM, respecting the DD/MM/YY, HH:mm format we defined before:
12/02/17, 12:42
- Change the stat template into this:
<span class="date"> <span class="label">Created</span> <span class="value">{{ selectedNote.created | date }}</span> </span>
We should have the date nicely formatted and displayed in our app:

- Learning Single:page Web Application Development
- PHP 從入門到項目實踐(超值版)
- Android Studio Essentials
- Rake Task Management Essentials
- 數據結構習題精解(C語言實現+微課視頻)
- 區塊鏈:以太坊DApp開發實戰
- Podman實戰
- Getting Started with NativeScript
- Unity 5 for Android Essentials
- 執劍而舞:用代碼創作藝術
- C/C++程序員面試指南
- Julia for Data Science
- Spring Boot+MVC實戰指南
- Python:Deeper Insights into Machine Learning
- 動手打造深度學習框架