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?
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.
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.
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.
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+).
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:
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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With