vue3 watchEffect用法以及清除副作用
传入一个对象,定义get,set方法二,侦听数据的变化watchEffect: 用于自动收集响应式数据的依赖watch: 手动指定侦听的数据源具体用法:可以获取watchEffect返回值函数,调用该函数即可...
·
一.computed
comdwd用法主要是:当一些属性需要依赖一个状态的时候,可以使用computed属性处理
- Options API中 computed主要是配置的选项
- Compostion API中 可以直接在setup函数中编写
具体用法:
-
接受一个getter函数 直接返回一个ref对象 ,代码实现:
<template>
<div>
<h1>{{Info}}</h1>
<button @click="updataInfo">修改</button>
</div>
</template>
<script>
import { reactive, toRefs,ref } from '@vue/reactivity'
import { computed } from '@vue/runtime-core'
export default {
setup(){
const obj =reactive({
name:"lisi",
age:18
})
let {name,age}=toRefs(obj);
const Info = computed(()=>name.value+""+age.value)
const updataInfo=()=>{
name.value="zhengyin"
age.value="20";
}
return{
updataInfo,
Info
}
}
}
</script>
<style lang="scss" scoped>
</style>
2. 传入一个对象,定义get,set方法
<template>
<div>
<h1>{{Info}}</h1>
<button @click="updataInfo">修改</button>
</div>
</template>
<script>
import { reactive, toRefs,ref } from '@vue/reactivity'
import { computed } from '@vue/runtime-core'
export default {
setup(){
const obj =reactive({
name:"lisi",
age:18
})
let {name,age}=toRefs(obj);
const Info = computed({
get:()=>name.value+""+age.value,
set:(newValue)=>{
const names = newValue.split(" ")
name.value = names[0];
age.value=names[1];
}
})
const updataInfo=()=>{
name.value="zhengyin"
age.value="20";
}
return{
updataInfo,
Info
}
}
}
</script>
<style lang="scss" scoped>
</style>
二,侦听数据的变化
watch主要用来侦听data,props的数据变化,而执行一些事情
- watchEffect: 用于自动收集响应式数据的依赖
- watch: 手动指定侦听的数据源
具体用法:
- 首先watchEffect传入的函数会立即执行一次,在执行的过程中收集依赖
- 只有收集的依赖发生变化时 函数才会再次执行
<template>
<div>
{{name}}
<button @click="updateMsg">修改</button>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue'
export default {
setup() {
const name = ref("zhangyin")
const age = ref(18)
const updateMsg = ()=>{
name.value="zhansga"
age.value++;
}
watchEffect(()=>{
console.log("name:",name.value);
})
return {
updateMsg,
name
}
}
}
</script>
<style lang="scss" scoped>
</style>
watchEffect停止侦听
可以获取watchEffect返回值函数,调用该函数即可
三,watchEffect清楚副作用
开发中需要在侦听函数中执行网络请求,但是在网络请求还没有达到的时候停止了侦听器,或者侦听器侦听函数被再次执行了,那么上一次的网络请求应该被取消掉这个时候可以清除上一次的副作用;
- 当副作用即将重新执行 或者 侦听器被停止 时会执行该函数传入的回调函数;
<template>
<div>
<p>{{name}}</p>
<p>{{age}}</p>
<button @click="updataName">改变</button>
</div>
</template>
<script>
import {ref, watchEffect } from 'vue'
export default {
setup(){
const name = ref("why")
const age = ref(18)
const stop= watchEffect((onInvalidate)=>{
const timer = setTimeout(()=>{
console.log("网络请求成功");
},2000)
onInvalidate(()=>{
clearTimeout(timer)
})
console.log("name:",name.value,"age:",age.value);
})
const updataName =()=>{
name.value="wangwy",
age.value++;
}
return{
updataName,
name,
age
}
}
}
</script>
<style lang="scss" scoped>
</style>
更多推荐
已为社区贡献2条内容
所有评论(0)