vue的计算属性

一、基础用法只有getter

代码写法简单,在getter函数内return计算结果。

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
// 计算属性的 getter fullName:
function () {
// 1、`this` 指向 vm 实例
// 2、return计算结果
return this.firstName + ' ' + this.lastName } } })

 

二、高级用法增加setter

// ...
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}
// ...

现在再运行 vm.fullName = 'John Doe' 时,setter 会被调用,vm.firstName 和 vm.lastName也会相应地被更新;进而会触发getter被调用

相关文章:

  • 2021-11-28
  • 2021-09-10
  • 2022-12-23
  • 2022-12-23
  • 2021-05-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 1970-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-10-14
相关资源
相似解决方案