computed: 当依赖的属性值发生变化的时候会触发并重新计算, 当属性值无变化时取缓存数据,computetd支持缓存;组件第一次渲染时会触发;不支持异步操作。
watch:无缓存,监听data中数据的变化,支持异步操作。
deep:true;开启深度监听对象,消耗性能; 监听对象不开启deep不能监听到对象子属性的变化;
immediate:true;组件初次创建是否触发监听,默认false不触发监听。
computed使用
<template>
<div class="hello">
<p>computed:{{sum}}</p>
<p>方法获取:{{getSum()}}</p>
<p>computed setAndGet:{{fullName}}</p>
</div>
</template>
export default {
data () {
return {
score1: 93,
score2: 90,
score3: 80,
firstName: 'cheng',
lastName: 'yuan'
}
},
methods: {
// 通过方法获取分数的总和,每次使用的时候调用getsum方法,都会重新计算
getSum () {
return this.score1 + this.score2 + this.score3
}
},
mounted () {
setTimeout(() => {
this.lastName = "yuanyuan" // 修改这个属性会执行get方法
this.fullName = 'cheng yuanyuan' //修改这个属性会执行set方法再次执行get方法
}, 1000 * 5)
},
computed: {
// getSum 和 computed中的sum都能获取到最终结果。
// computed 多次访问sum不会再次执行函数,只有sum所依赖的值发生改变的时候,才会重新求值;(通 过getSum获取,每调用一次都会执行一次方法);
// 不需要在data中声明属性,可以直接访问sum;
sum: function () {
return this.score1 + this.score2 + this.score3
},
// getter和setter的使用 ---------------------
// 计算属性默认只有getter方法;可以设置setter方法,个人感觉setter用处不大,下面我是从vue官网看到的代码,在fullName中增加get 和 set方法
// 再重新给fullName赋值,从而触发set方法,然后分别修改firstName和lastName,再次执行get方法;感觉跟直接给firstName和lastName赋值没有区别
fullName: {
get: function () {
return this.firstName + this.lastName
},
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[1]
}
}
}
}
</script>
watch使用:
export default {
data () {
return {
watchText: 'initValue',
watchObj: {name: 'zhangsan', age: 30},
}
},
methods: {
},
mounted () {
setTimeout(() => {
this.watchText = 'changeValue'
this.watchObj.name = 'newZhangsan'
}, 1000 * 5)
},
watch: {
// 监听一个属性
watchText (newValue, oldVal) {
console.log(newValue)
},
// 监听对象需要使用deep,默认是监听不到对象中属性的
watchObj: {
handler (newValue, oldVal) {
console.log(newValue)
},
deep: true,
// 默认值为false,第一次绑定值的时候不会监听到,只有值发生改变的时候才会被监听到。
// 如果想要第一次绑定值的时候被监听,可以设置为ture;
immediate: true
},
// 深度监听对象,对象的每个属性变化都会执行handler,如果执行监听对象的某个属性,方法如下:
// 写法1:
'watchObj.name': {
handler (newValue, oldName) {
console.log(newValue, '写法1')
}
},
// 写法2:
'watchObj.name' (newValue, oldVal) {
console.log(newValue, '写法2')
}
},
}
</script>