案例:有两个变量,firstName 和 lastName, 希望他们拼接之后在界面上显示;
1.采用模板语法
<h2>{{ firstName + " " + lastName}}</h2>
模板中存在大量的复杂逻辑,不便于维护
2.采用computed 和 methods方法
HTML中代码
<template>
<div>
<h2>{{getFullName()}}</h2>
</div>
</template>
JavaScript中代码
computed: {
fullName () {
return this.firstName + " " + this.lastName
}
methods: {
getFullName () {
return this.firstName + " " + this.lastName
}
}
采用computed 和 method 都可以,但是更推荐computed
理由:
// 计算属性是有缓存的,当我们多次使用计算属性时,计算属性中的运算只会执行一次
// 计算属性会随着依赖的数据发生变化,在使用时,计算属性依然会重新进行计算
computed 的核心 setter 和 getter
computed: {
// 计算属性用函数和用对象的区别
// 用函数:只有getter
// 用对象:有getter 和 setter
// fullName的getter方法:
fullName: function () {
return this.firstName + " " + this.lastName
},
//fullName的getter和setter方法
fullName: {
get: function () {
return this.firstName + " " + this.lastName
},
//一旦给计算属性赋值,会调用计算属性中的set方法
set: function (newValue) {
console.log(newValue);
const names = newValue.split(" ")
this.firstName = names[0];
this.lastName = names[1]
}
}
}