计算属性和侦听器
计算属性
定义
new Vue({
el: "#app",
data: () => ({
edge: 10
}),
// ...
computed: {
area() {
return this.edge * this.edge;
}
}
})
计算属性是基于它们的响应式依赖进行缓存的,提高效率
使用 setter
new Vue({
el: "#app",
data: () => ({
edge: 10
}),
// ...
computed: {
area: {
get: function() {
return this.edge * this.edge;
},
set: function(newEdge) {
this.edge = Math.sqrt(newEdge);
}
}
},
methods: {
test() {
this.area = 25; // 调用 test 方法时, this.edge 会改为 5
}
}
})
计算属性 VS 方法
计算属性会在依赖的响应式数据改变时更新缓存的值(高效)
方法会在每次获取时重新执行方法(实时)
侦听器
定义
new Vue({
el: "#app",
data: () => ({
count: 1
}),
methods: {
inc() {
this.count++;
}
},
watch: {
// 如果 count 改变,这个函数就会运行,第一个参数为新的 count 值,第二个参数为旧的 count 值
count: function(newCount, oldCount) {
console.log("NewCount Value: " + newCount, "OldCount Value: " + oldCount, "ThisCount Value: " + this.count) // this.count 为已经更新了的值
},
// 如果使用箭头函数则访问不到 this
// count: (newCount, oldCount) => {
// console.log("NewCount Value: " + newCount, "OldCount Value: " + oldCount, "ThisCount Value: " + this.count) // this.count 为未定义, 因为箭头函数内部的 this 就是定义时的上下文,使用这里是 Window 对象
// }
}
})
深度监听
<div>
<div>侦听器1调用次数:{{ watch1Count }}</div>
<div>侦听器2调用次数:{{ watch2Count }}</div>
<button @click="change">改变</button>
</div>
new Vue({
el: "#app",
data: () => ({
obj1: {
attr1: 1,
attr2: 2
},
obj2: {
attr1: 1,
attr2: 2
},
watch1Count: 0,
watch2Count: 0,
}),
methods: {
change() {
this.obj1.attr1++; // 不会触发 obj1 的侦听
this.obj2.attr1++; // 会触发 obj2 的侦听
}
},
watch: {
obj1: {
handler() {
this.watch1Count++;
}
},
obj2: {
handler() {
this.watch2Count++;
},
deep: true // 当侦听对象的属性改变时也会调用 handler 进行处理
},
}
})
在改变数据前监听
new Vue({
el: "#app",
data: () => ({
count: 1
}),
methods: {
inc() {
this.count++;
}
},
watch: {
// 如果 count 改变,这个函数就会运行,第一个参数为新的 count 值,第二个参数为旧的 count 值
count: {
handler(newCount, oldCount) {
console.log("NewCount Value: " + newCount, "OldCount Value: " + oldCount, "ThisCount Value: " + this.count) // this.count 为更新后的值
},
immediate: true // 会在侦听开始时立即侦听一次,第一次执行时 oldCount 为未定义
},
}
})
对数组的侦听
new Vue({
el: "#app",
data: () => ({
array: [{
name: "Wen"
}]
}),
methods: {
push() {
this.array.push(this.array.length + 1)
},
change() {
this.array[0].name = "Tang" + Date.now() // 只会调用 deep 侦听
// 如果需要直接更新数组的值,只能使用下面的这种方法或者调用数组的方法
// Vue.set(this.array, 0, this.array[0] + 1)
},
},
watch: {
// 如果 count 改变,这个函数就会运行,第一个参数为新的 count 值,第二个参数为旧的 count 值
array: [
function (newValue, oldValue) {
console.log("New Value: " + newValue, "Old Value: " + oldValue, "This Value: " + this.array) // 这几个值完全一致
},
{
handler(newValue, oldValue) {
console.log("New Value: " + newValue, "Old Value: " + oldValue, "This Value: " + this.array) // 这几个值完全一致
},
deep: true
}
],
}
})
数组可以监听的一些方法:
push
: 尾部添加pop
: 尾部删除unshift
: 头部添加shift
: 头部删除splice
: 删除、添加、替换,第一个参数起始索引,删除的数量,要添加的元素1,要添加的元素2…reverse
: 逆序数组