计算属性的setter和getter

546 阅读1分钟

最近在学习vue3当中的Compositon API,编写setup函数中使用computed来编写一个计算属性时,复习到了getter和setter方法,对之前模糊的印象有了更深刻的理解: 计算属性computed可以传入两种参数:函数(就是一个getter方法)和一个对象(此时必须写入getter和setter)

对于属性的获取一般称为getter

  • 在很多情况下computed一般只需要getter方法,所以有时候会将计算属性写成一个函数(此时计算属性就是一个getter方法);
    // fullName的getter方法 =fullName:function(){}
    fullName () {
      return this.firstName + '' + this.lastName
    }
  }


  • computed中getter和setter的完整写法
       get:function () {
         return this.firstName +""+ this.lastName
       },
       set:function (newValue) {
         console.log(newValue)
       }
     }

01.png

对于属性的设值一般称为setter

可以从代码中看出setter是设置值计算属性的值的;

      get: function () {
        console.log('使用了getter')
        return this.firstName + '' + this.lastName
      },
      set: function (newValue) {
        console.log(newValue)
        const names = newValue.split('')
        this.firstName = names[0]
        this.lastName = names[1]
      }
    }
  },
  methods: {
    changeFullName () {
      this.fullName = 'he'
    }
  }

02.png

03.png

总结

计算属性中的getter是获取值的,setter是设置计算属性的值的;

以上是自己的一些总结和笔记,总结的不足之处和理解不对的地方欢迎指出讨论。