4

vue 的 computed 里面的函数为什么要绑定成 property,而不是绑定成 method

 2 years ago
source link: https://www.v2ex.com/t/838970
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Vue.js

vue 的 computed 里面的函数为什么要绑定成 property,而不是绑定成 method

  git00ll · 18 小时 2 分钟前 · 516 次点击

绑定到 property 的话,使用时不要加括号,但是在定义 computed 时是函数。 绑定成 method 不是更清晰吗?我觉得绑定成 method 也是能实现缓存计算的。 难道是作者的个人风格

4 条回复    2022-03-09 14:08:10 +08:00

cxe2v

cxe2v      17 小时 52 分钟前

computed 里的属性都有数据绑定,在数据变更时,对应的 computed 属性也会收到更新通知并发出自己的更新通知,

method 里的方法不会在使用的数据有更新时,主动更新自己的结果

rabbbit

rabbbit      17 小时 40 分钟前

computed 里的函数其实是个 getter
也可以这么写:

{
  computed: {
   bar: {
    get() {
     return this.foo
   },
    set(value) {
     this.foo = value
   }
  }
 },
}

想作为函数调用也行,可以这么写:
{
  computed: {
   bar: {
    get() {
     return () => {
      return this.foo + 1;
    };
   },
  },
 },
}

waiaan

waiaan      7 小时 26 分钟前

只是为了区分开吧,有的需要监听,有的不需要监听。

faceRollingKB

faceRollingKB      2 小时 23 分钟前

computed 本身就是为了扩展 data ,设计成 property 是最合适的,跟 method 没什么关系;而且要是调方法也有缓存,你 debugger 的时候岂不是心里一万个草泥马么?

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK