Created date with a filter

We will now display the creation date of the selected note in the status bar.

  1. In the status bar div 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.

  1. 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.

  1. 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
  1. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.211.134