Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vuejs computed

对于任何复杂逻辑,都应当使用计算属性 计算属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值。 如果你不希望有缓存,请用方法来替代。

计算属性的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 也相应地会被更新

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment