当前位置:网站首页>watch VS watchEffect
watch VS watchEffect
2022-07-27 14:15:00 【Lyrelion】
Catalog
How to monitor for the first time , Automatically cancel watch monitor ?
If you need to track multiple responsive variables , Is there any good solution ?
Whether it is necessary to manually pass in dependencies
Every time you listen for dependencies The value returned
Use onInvalidate() eliminate watchEffect side effect
Use watchEffect Back to stop Method , stop it watchEffect monitor
Use flush modify watchEffect The time to listen
How to use watch ?
Vue Options API Provides a watch Options
export default {
data () {
return {
title: 'Vue2'
}
},
watch: {
// Watcher
}
}
watch: {
title: {
handler: (newTitle, oldTitle) => {
console.log("Title changed from " + oldTitle + " to " + newTitle);
},
immediate: true,
},
},Applicable scenario :
- You need to control which dependencies trigger this method
- You need to access the previous value
How to monitor for the first time , Automatically cancel watch monitor ?
call watch Oneself , This requirement can be realized
/**
* monitor vuex Developer configuration changes in
*/
const watchInitData = watch(
() => store.state[VuexModule.ApplicationLibDevelopment],
async (newVal) => {
// Page initialization
initPage();
// call watch In itself , You can cancel listening
watchInitData();
},
{ deep: true },
);If you need to track multiple responsive variables , Is there any good solution ?
stay Vue Options API(Vue2) in , You can create multiple watch The observer
stay Composition API(Vue3) in , You can create multiple watchEffect The observer ; You can also create only one watchEffect, But in his callback function , Write all the values to be monitored
watchEffect VS watch
Whether it is necessary to manually pass in dependencies
watch —— It is necessary to specify the monitored properties , Also indicate the monitored callback 【 The dependency needs to be passed in manually 】
watchEffect —— It is not necessary to specify which attribute to monitor , Which property is used in the monitored callback , Then monitor which attribute 【 There is no need to pass in dependencies manually , Will automatically get from the callback function 】
Whether it is inert
watch It's inert. —— Only when the dependency changes , Will trigger ; It can be for watch Pass a immediate attribute , Make it run at initialization
watchEffect Non inert —— Run immediately after creating the component , meanwhile , Run when any dependencies of the method change
Every time you listen for dependencies The value returned
wach —— Every time I listen , Will return old and new values
watchEffect —— Every time I listen , Only the latest value will be returned ; Only when the page is initialized , To get an old value
watchEffect VS computed
watchEffect and watch equally , It's kind of like computed
- computed Pay attention to the calculated value ( The return value of the callback function ), So you have to write the return value
- watchEffect It's about the process ( The body of the callback function ), So you don't have to write the return value
How to use watchEffect ?
- Run immediately when initializing the component ( When the component is initialized ,watchEffect Will run and record the starting value )
- Run when dependencies change ( When The value of the listening object When the change , It will trigger watchEffect)
From the second point : It's mounting DOM Before , Try not to visit DOM, Prevent unnecessary monitoring
import { ref, watchEffect } from 'vue'
export default {
setup () {
const userID = ref(233)
watchEffect(() => console.log('userID: ' + userID.value))
setTimeout(() => {
userID.value = 666
}, 500)
return {
userID
}
}
}
// Print the results
userID: 233
userID: 666It can also be in components , Use watchEffect combination props To use
export default {
props: {
movieID: String,
},
setup(props) {
watchEffect(() => console.log(props.movieID))
},
}Use onInvalidate() eliminate watchEffect side effect
whenever watchEffect When listening for dependency changes , Just execute an asynchronous request ;
But before the asynchronous request completes , The dependencies have changed again ……
How to avoid sending a request again ?
export default {
setup() {
watchEffect(onInvalidate => {
// Asynchronous requests
const apiCall = someAsyncMethod(props.songID)
onInvalidate(() => {
// Cancel asynchronous request
apiCall.cancel()
})
})
}
}Use watchEffect Back to stop Method , stop it watchEffect monitor
It can be stopped manually watchEffect monitor
Just imagine , If you want to observe a dependency , Until he becomes a certain value , I don't want to continue listening
Continuing to monitor is a waste of resources , How to realize manual stop watchEffect monitor ?
watchEffect Back to stop Method , Call it , It can be stopped manually watchEffect monitor
export default {
setup (props) {
let stopWatcher = watchEffect(() => console.log(props.movieID))
stopWatcher()
}
}Use flush modify watchEffect The time to listen
watchEffect By default, before the component is loaded , Will call a monitor , Take a chestnut :
const state = reactive({
test: {
myName: '',
}
});
state.test.myName = 'Lyrelion'
watchEffect(() => {
console.log(' The name has been changed ', state.test.myName );
})
/**
* Print the results ( Before component update ,watchEffect Just perform a monitoring , So it prints twice )
* The name has been changed
* The name has been changed Lyrelion
*/
If before the component is loaded , I don't want to monitor ? in other words , modify watchEffect Monitoring opportunity
It can be modified by watchEffect Medium flush attribute , Specify the listening time
flush There are three settable items :
- pre ( Default )
- post ( Trigger after the component is rendered , Access the loaded DOM, This prevents the initial value from being attached , Began to monitor the problem )
- sync ( And watch equally , Every change forces the listener to be triggered , It's inefficient , There should be little need for )
in summary , In order to... Before the component is loaded , Do not perform listening , It can be written like this
const state = reactive({
test: {
myName: '',
}
});
state.test.myName = 'Lyrelion'
watchEffect(() => {
console.log(' The name has been changed ', state.test.myName );
}, {
flush: 'post'
})
/**
* Print the results ( Before component update ,watchEffect Just perform a monitoring , So it prints twice )
* The name has been changed Lyrelion
*/
Add a well written article
边栏推荐
- [luogu_p4820] [national training team] stack [mathematics] [physics] [harmonic progression]
- Travel notes from July 11 to August 1, 2022
- [training day4] sequence transformation [thinking]
- One of yolox improvements: add CBAM, Se, ECA attention mechanism
- Zhishang technology IPO meeting: annual revenue of 600million, book value of accounts receivable of 270Million
- Unity3D学习笔记10——纹理数组
- printf函数缓冲区问题
- 知识关联视角下金融证券知识图谱构建与相关股票发现
- A Keypoint-based Global Association Network for Lane Detection
- Wechat campus laundry applet graduation design finished product (4) opening report
猜你喜欢

Recommended collection, confusing knowledge points of PMP challenge (2)

利用C语言实现URL解析的基本方法之优秀

Interview eight part essay · TCP protocol

【idea】设置提取serialVersionUID

基于C语言实现线性表的建立、插入、删除、查找等基本操作

认知篇----硬件工程师的成才之路之经典

Cognition -- classic of the road to success of hardware engineers
![[luogu_p4556] [Vani has an appointment] tail in rainy days / [template] segment tree merging](/img/e3/c2b3d45c6a0d1f7ff0b8b7bccf2106.png)
[luogu_p4556] [Vani has an appointment] tail in rainy days / [template] segment tree merging

井贤栋等蚂蚁集团高管不再担任阿里合伙人 确保独立决策

西测测试深交所上市:年营收2.4亿募资9亿 市值47亿
随机推荐
Named entity recognition of Chinese electronic medical records based on Roberta WwM dynamic fusion model
[training day3] reconstruction of roads [SPFA]
Weice biological IPO meeting: annual revenue of 1.26 billion Ruihong investment and Yaohe medicine are shareholders
RTL8762DK 环境搭建(一)
初学者入门:使用WordPress搭建一个专属自己的博客
watch VS watchEffect
<C> C语言哈希表使用
解气!哈工大被禁用MATLAB后,国产工业软件霸气回击
Various ways to use new
West test Shenzhen Stock Exchange listing: annual revenue of 240million, fund-raising of 900million, market value of 4.7 billion
Chapter3 data analysis of the U.S. general election gold offering project
关于max做动画的一些关键信息(shift+v)
阻塞队列BlockingQueue
va_list 使用总结
SLAM综述阅读笔记七:Visual and Visual-Inertial SLAM: State of the Art, Classification,and Experimental 2021
力扣SQL语句习题,错题记录
[training day4] sequence transformation [thinking]
基于C语言的LR1编译器设计
平板模切机
HDU4496 D-City【并查集】