Vue2的computed属性用于计算派生出的数据,它的值是一个函数,该函数返回的值会被缓存,只有相关依赖发生改变时才会重新计算。

在Vue2中,computed属性可以定义为对象,也可以定义为函数。

定义为对象时,其属性名为计算属性的名称,属性值为计算属性的函数体。

例如:

computed: {
  fullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
}

定义为函数时,其函数体中的return语句即为计算属性的值。

例如:

computed() {
  return this.firstName + ' ' + this.lastName;
}

在模板中使用computed属性时,可以直接在模板中使用计算属性的名称,不需要调用函数。

例如:

<template>
  <div>
    <p>{{fullName}}</p>
  </div>
</template>

在计算属性中还可以使用set方法,用于设置计算属性的值。当使用set方法设置计算属性的值时,会触发计算属性的相关依赖更新。

例如:

computed: {
  fullName: {
    get: function() {
      return this.firstName + ' ' + this.lastName;
    },
    set: function(newValue) {
      var names = newValue.split(' ');
      this.firstName = names[0];
      this.lastName = names[names.length - 1];
    }
  }
}
vue2的computed用法

原文地址: https://www.cveoy.top/t/topic/1ab 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录