Vue的计算属性(computed)和方法(methods)有什么区别

方法其实是调用的计算属性的getter方法;

// 在组件中
methods: {
  fullName: function () {
    return this.firstName + ' ' + this.lastName
  }
}

计算属性默认只有 getter ,不过在需要时你也可以提供一个 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]
    }
  }
}
// ...

另外 如果返回值不变,computed是有缓存的,所以性能比methods要好

推荐 Vue中条件渲染v-if和v-show有什么区别

猜你喜欢

转载自blog.csdn.net/weixin_38289787/article/details/103485088