当前位置:网站首页>2021-05-20computed和watch应用与区别
2021-05-20computed和watch应用与区别
2022-06-24 07:06:00 【隐密修罗】
VUE之computed和watch应用与区别 目录:
** watch 和 computed**
conputed 作用:
计算结果并返回,只有当被计算的值发生改变时才会触发
(即:计算属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算,具有依赖属性.
(如果你在name方法下打印时间 new Data() 多次打印是一样的,因为new Data() 不是依赖型数据 )
new Vue({
el: '#id',
template: `<div> <span>Name: {
{name}}<span> </div>`,
data: {
firstName: 'Leo',
lastName: 'Alan'
},
computed: {
name () {
return `${
this.firstName} + ${
this.lastName}`
}
}
})
watch 作用:
监听某一个值,当被监听的值发生变化时,执行对应的操作,如下面的单个单个的监听值,然后再改变data的值或者做其他操作
(与computed的区别是,watch更加适用于监听某一个值的变化并做对应的操作,比如请求后台接口等,而computed适用于计算已有的值并返回结果)
(如果你在name方法下打印 new Data() 多次打印是不一样的,因为watch一根筋,每次都进行更新执行 )
new Vue({
el: '#id',
template: `<div> // ... </div>`,
data: {
firstName: 'Leo',
lastName: 'Alan',
obj1: {
a: 0
}
},
watch: {
// 监听firstName,当firstName发生变化时就会执行该函数
firstName () {
// 执行需要的操作...
// 注:初始化不会执行,只有当被监听的值(firstName)发生变化时才会执行
},
// 监听lastName
lastName: {
handler (newName, oldName) {
// 执行需要的操作...
},
immediate: true // true: 初始化时就会先执行一遍该监听对应的操作
},
obj1: {
handler () {
// 执行需要的操作...
},
deep: true // 该属性默认值为false.
// 当被监听的值是对象,只有deep为true时,对应属性的值(obj1.a)发生变化时才能触发监听事件,但是这样非常消耗性能
},
// 监听对象具体的属性, deep就不需要设置为true了
'obj1.a': {
handler () {
// 执行需要的操作...
}
}
}
})
注意: 不要在computed和watch中修改被依赖(或者被监听)的值,这样可能会导致无限循环
边栏推荐
猜你喜欢

Send custom events in QT

中国芯片独角兽公司

js中通过key查找和更新对象中指定值的方法

New technology practice, encapsulating the permission application library step by step with the activity results API

ZUCC_编译语言原理与编译_实验06 07 语法分析 LL 分析

Permission model DAC ACL RBAC ABAC

一文讲透,商业智能BI未来发展趋势如何

分布式 | 如何与 DBLE 进行“秘密通话”

成为IEEE学生会员

Xiaohei ai4code code baseline nibble 1
随机推荐
There was an error checking the latest version of pip
Vscode install the remote -wsl plug-in to connect to the local WSL
String转Base64
5 minutes, excellent customer service chat handling skills
liunx 更改 vsftpd 的端口号
ZUCC_编译语言原理与编译_实验06 07 语法分析 LL 分析
Qt 中发送自定义事件
教程篇(5.0) 08. Fortinet安全架构集成与FortiXDR * FortiEDR * Fortinet 网络安全专家 NSE 5
[untitled]
Introduction to NC machine tool programming [G-code]
Several schemes of PHP code encryption
How to mount a USB hard disk with NTFS file format under RHEL5 system
Increase insert speed
JS merge multiple objects and remove duplicates
MATLAB Camera Calibrator相机标定
QPS, TPS, concurrent users, throughput relationship
Matlab求解线性方程组Ax=b
Variable declaration and some special variables in shell
Get screen width and height tool class
Base64编码详解及其变种(解决加号在URL变空格问题)