在模板中使用getter比方法更加高效和易于维护。在Getter中定义计算属性,模板只读取其值,而不会对应用程序进行多次计算。下面是一个使用getter的例子:
// 组件类中定义 getter
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
在模板中使用getter:
FullName: {{ fullName }}
相比之下,使用方法可能会导致多次计算,因为方法每次调用都会重新计算。例如:
// 组件类中定义方法
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
在模板中使用方法:
FullName: {{ getFullName() }}
因为Getter在组件初始化时只会计算一次,所以使用Getter比方法更加高效和易于维护。