官术网_书友最值得收藏!

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

  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:

主站蜘蛛池模板: 桃江县| 昂仁县| 云安县| 乌兰浩特市| 贡山| 专栏| 澎湖县| 虎林市| 林州市| 铜山县| 呼伦贝尔市| 邹城市| 巩义市| 滕州市| 房产| 水富县| 潮州市| 沭阳县| 五原县| 叙永县| 砀山县| 沅江市| 敦化市| 辽中县| 凉城县| 县级市| 樟树市| 松桃| 六盘水市| 茌平县| 聂荣县| 伊金霍洛旗| 丹凤县| 仪征市| 介休市| 新干县| 乐平市| 桃园县| 宁国市| 龙里县| 普洱|