V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
git00ll
V2EX  ›  Vue.js

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

  •  
  •   git00ll · Mar 8, 2022 · 2405 views
    This topic created in 1515 days ago, the information mentioned may be changed or developed.

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

    4 replies    2022-03-09 14:08:10 +08:00
    cxe2v
        1
    cxe2v  
       Mar 8, 2022
    computed 里的属性都有数据绑定,在数据变更时,对应的 computed 属性也会收到更新通知并发出自己的更新通知,

    method 里的方法不会在使用的数据有更新时,主动更新自己的结果
    rabbbit
        2
    rabbbit  
       Mar 8, 2022
    computed 里的函数其实是个 getter
    也可以这么写:

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

    想作为函数调用也行,可以这么写:
    {
      computed: {
       bar: {
        get() {
         return () => {
          return this.foo + 1;
        };
       },
      },
     },
    }
    waiaan
        3
    waiaan  
       Mar 9, 2022
    只是为了区分开吧,有的需要监听,有的不需要监听。
    faceRollingKB
        4
    faceRollingKB  
       Mar 9, 2022
    computed 本身就是为了扩展 data ,设计成 property 是最合适的,跟 method 没什么关系;而且要是调方法也有缓存,你 debugger 的时候岂不是心里一万个草泥马么?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2598 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 06:10 · PVG 14:10 · LAX 23:10 · JFK 02:10
    ♥ Do have faith in what you're doing.