本文主要是介绍从新回归Vue之3.0(三)Watch,WatchEffect,生命周期,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一,Watch和WatchEffect使用方法
类似于之前的Watch监听,推荐watch监听
1、watch和watchEffect都懒执行副作用,不过watchEffect比较频繁,在vue组件更新之前执行; 2、watch更具体地说明什么状态应该触发侦听器重新运行,watchEffect就没有这么友好; 3、watch访问侦听状态变化前后的值。
<template><p>{{ count }}</p><p>{{ originData.count }} {{ originData.user.name }}</p><button @click="incriment">点击我count增加</button>
</template><script setup lang="ts">
import { ref, reactive, watchEffect, watch } from "vue";
// data
const count = ref(0);
const user = reactive({ name: "张三" });
const arr = reactive([1, 2, 3, 4]);
const originData = reactive({count: 0,user: {name: "张三",},arr: [1, 2, 3, 4],
});
// props
// emit
// methods
const incriment = () => {console.log(originData.user);originData.count++;count.value++;originData.user.name = "李四";
};
//watch
watch([count, originData.user],(newVals, oldVals) => {console.log("newVals", newVals);console.log("oldVals", oldVals);},{deep: true,immediate: true,}
);
// defineExpose
</script>
二,在setup中的生命周期钩子
因为 setup
是围绕 beforeCreate
和 created
生命周期钩子运行的,所以不需要显式地定义它们。换句话说,在这些钩子中编写的任何代码都应该直接在 setup
函数中编写。
选项式 API | Hook inside setup |
---|---|
beforeCreate | Not needed* 不需要 |
created | Not needed* 不需要 |
beforeMount | onBeforeMount 挂载之前 |
mounted | onMounted 页面加载完成时执行 |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted 页面销毁时执行 |
errorCaptured | onErrorCaptured |
renderTracked | onRenderTracked |
renderTriggered | onRenderTriggered |
activated | onActivated |
deactivated | onDeactivated |
import { onMounted, onActivated, onUnmounted, onUpdated, onDeactivated } from "vue";
// 生命周期
onMounted(() => {console.log("组件挂载");
});onUnmounted(() => {console.log("组件卸载");
});onUpdated(() => {console.log("组件更新");
});
onActivated(() => {console.log("keepAlive 组件 激活");
});onDeactivated(() => {console.log("keepAlive 组件 非激活");
});
这篇关于从新回归Vue之3.0(三)Watch,WatchEffect,生命周期的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!