vue中模板内的表达式非常便利,如:
<div>我和科比合砍{{myScore + KobeScore}}分</div>
data(){
return {
myScore: 0,
KobeScore: 81
}
},
但是设计他们的初衷时用于简单的运算,在模板中放入太多的逻辑会让模板过重且难以维护,此时就可以考虑计算属性和监听器。
computed和watch的简单使用
computed:
<div>我和科比合砍{{totalScore}}分</div>
data(){
return {
myScore: 0,
KobeScore: 81
}
},
computed: {
totalScore(){
return this.myScore + this.KobeScore
}
},
<div>科比今日得分:{{kobeScore}}分</div>
data(){
return {
section1: [{ name: 'Kobe', score: 14 }],
section2: [{ name: 'Kobe', score: 12 }],
section3: [{ name: 'Kobe', score: 27 }],
section4: [{ name: 'Kobe', score: 28 }]
},
computed: {
kobeScore(){
return this.section1.filter(item => item.name === 'Kobe')[0].score
+ this.section2.filter(item => item.name === 'Kobe')[0].score
+ this.section3.filter(item => item.name === 'Kobe')[0].score
+ this.section4.filter(item => item.name === 'Kobe')[0].score
}
},
watch(下面的写法要被侦听、监听的数据发生改变时才生效)
<div>我和科比合砍{{totalScore}}分</div>
data(){
return {
myScore: 0,
KobeScore: 81,
totalScore: 0 // 在data中声明totalScore
}
},
watch: {
myScore (newValue, oldValue) {
console.log(newValue, oldValue)
this.totalScore = newValue + this.KobeScore
},
KobeScore (newValue, oldValue) {
console.log(newValue, oldValue)
this.totalScore = newValue + this.myScore
}
},
下面的写法在数据(myScore和KobeScore)没改变的时候也会计算一次
<div>我和科比合砍{{totalScore}}分</div>
data(){
return {
myScore: 0,
KobeScore: 81,
totalScore: 0 // 在data中声明totalScore
}
},
watch: {
myScore: {
immediate: true, // 为true时会自动计算一次
// deep: true, // 为true时可以监听到对象里的属性的变化,数组(一维、多维)的变化不需要通过深度监听,对象数组中对象的属性变化则需要deep深度监听。
handler(newValue, oldValue){
console.log(newValue)
console.log(oldValue)
this.totalScore = newValue + this.KobeScore
}
},
KobeScore: {
immediate: true,
handler(newValue, oldValue){
console.log(newValue)
console.log(oldValue)
this.totalScore = newValue + this.myScore
}
}
},
从上面的代码你可以发现使用watch获取totalScore需要监听两个值而computed一个函数就返回了。下面我们来对computed和watch做一个对比:
- 处理数据的场景不同,watch适合一个数据影响多个数,computed适合一个数据受多个数据影响;
- ** 计算属性有缓存性 ** ,计算所得的值如果没有变化不会重复执行(建议computed可以实现的适合使用computed);
- watch选项提供了更通用的方法,适合执行异步操作或较大开销操作的情况。
下面的写法可以针对对象的某一个属性进行监听,比如我现在只关注选手的得分的变化
data(){
return {
Kobe: {
name: 'Kobe Bean Bryant',
nickname: 'Black Mamba, 小飞侠',
scoreToday: '81'
},
scoreToday: 0
},
watch: {
'Kobe.scoreToday': {
// immediate: true,
handler(newValue, oldValue){
console.log(newValue)
console.log(oldValue)
this.scoreToday = newValue
}
}
},