Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between filters and methods in vue.js?

I want to convert a timestamp to Beijing time. Should I use a filter or a method to implement this feature? What's the difference, such as the difference in performance?

like image 657
Qun Avatar asked Dec 22 '17 10:12

Qun


People also ask

What is filters in VueJS?

A Filter is a simple JavaScript function which is used to change the output of a data to the browser. Filters in Vue. JS don't change the data directly wherever we store them, it only applies formatting to our data. The data remains the same only the output of a data to a browser is changed.

What is Methods in VueJS?

A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.

What is difference between method and computed in VueJS?

A computed property is cached, which implies that, for accessing data, the function runs just once if the value remains unchanged. Methods, on the other hand, need to run data properties checks every time, because they cannot tell otherwise if the values are changed inside the method property.

What are the common use of Vue filters?

Filters are a functionality provided by Vue. js that allows us to define filters that can be used to apply common text formatting. Filters can be used in two places: v-bind expressions and mustache interpolation (the first is supported in 2.1. 0+).


1 Answers

The displayed Beijing time only has to change when the underlying timestamp is changed. Methods should therefore not be used. Instead use computed properties or filters:

Using a computed property

new Vue() {
  data: {
    time: /* Your timestamp */
  },
  computed: {
    displayedTime() {
      /* Convert `this.time` to Beijing time */
    }
  }
}

In your template you can then do this:

{{ displayedTime }}

While this solution works, you can only use it for one timestamp (in this case time). Let's take a look at how you could do this with filters:

Using a filter

new Vue() {
  data: {
    time: /* Your timestamp */
  },
  filters: {
    displayedTime(timestamp) {
      /* Convert the `timestamp` argument to Beijing time */
    }
  }
}

In your template you can then do this:

{{ time | displayedTime }}

The advantage of this solution is that if you have another timestamp somewhere in your application you can use the same filter:

{{ otherTime | displayedTime }}

Make sure to use the Vue.filter() method if you want to make this filter work globally (outside of this Vue instance).

like image 65
Niklas Higi Avatar answered Oct 17 '22 22:10

Niklas Higi