Skip to content

Instantly share code, notes, and snippets.

@fanghm
Created September 29, 2017 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanghm/eeedad2e30d6ef381da0b9f46f7cc313 to your computer and use it in GitHub Desktop.
Save fanghm/eeedad2e30d6ef381da0b9f46f7cc313 to your computer and use it in GitHub Desktop.
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