vue.js 中的过滤器和方法有什么区别? [英] What is the difference between filters and methods in vue.js?

查看:62
本文介绍了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?

推荐答案

显示的北京时间只有在底层时间戳改变时才会改变.方法因此应该使用一>.而是使用计算属性或过滤器:

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

虽然此解决方案有效,但您只能将其用于一个时间戳(在本例中为 time).让我们来看看如何使用过滤器来做到这一点:

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

确保使用 Vue.filter() 方法,如果你想让这个过滤器全局工作(在这个 Vue 实例之外).

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

这篇关于vue.js 中的过滤器和方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆