程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

vue3中响应式侦听

发布于2021-12-05 19:13     阅读(704)     评论(0)     点赞(15)     收藏(4)


vue3提供了两个函数来侦听数据源的变化:watch和watchEffect

watch需要监听某个数据源,然后执行具体的回调函数,可监听单个数据源,也可以把多个值放在一个数组中进行侦听,最后的值也以数组形式返回。

watchEffect和watch的区别:

   1.watchEffect不需要手动传入依赖

   2.每次初始化时watchEffect都会执行一次回调函数来自动获取依赖

   3.watchEffect无法获取到原值,只能得到变化后的值

  1. <template>
  2. <div class="about">
  3. <h1>This is an about page</h1>
  4. </div>
  5. </template>
  6. <script>
  7. import { reactive, ref,watch, watchEffect } from "vue";
  8. export default {
  9. setup() {
  10. let num1 = ref(1);
  11. let num2 = reactive({
  12. year: 2021,
  13. });
  14. // 监听单个数据源
  15. watch(()=>num2.year,(newVal,oldVal)=>{
  16. console.log(newVal,oldVal);
  17. })
  18. // 监听多个数据源
  19. watch([()=>num2.year,num1],(newVal,oldVal)=>{
  20. console.log(newVal,oldVal);
  21. // 打印结果:[2022, 2][2021, 1]
  22. })
  23. // watchEffect和watch的区别:
  24. // 1.watchEffect不需要手动传入依赖
  25. // 2.每次初始化时watchEffect都会执行一次回调函数来自动获取依赖
  26. // 3.watchEffect无法获取到原值,只能得到变化后的值
  27. watchEffect(() => {
  28. console.log(num1.value);
  29. console.log(num2.year);
  30. });
  31. setInterval(() => {
  32. num1.value=2;
  33. num2.year=2022;
  34. }, 2000);
  35. return {
  36. num1,
  37. num2,
  38. };
  39. },
  40. };
  41. </script>

stop 停止监听,我们在组件中创建的watch监听,会在组件被销毁时自动停止。如果在组件销毁之前我们想要停止掉某个监听, 可以调用watch()函数的返回值

  1. setup() {
  2. let num1 = ref(1);
  3. let num2 = reactive({
  4. year: 2021,
  5. });
  6. const stop = watch([num1, () => num2.year], (newVal, oldVal) => {
  7. console.log(newVal, oldVal);
  8. // 打印结果:[2022, 2][2021, 1]
  9. });
  10. function jia() {
  11. num1.value++;
  12. num2.year++;
  13. }
  14. // 3秒后停止监听
  15. setInterval(() => {
  16. stop();
  17. }, 3000);

原文链接:https://blog.csdn.net/weixin_58347102/article/details/121679508




所属网站分类: 技术文章 > 博客

作者:西小口到了吗

链接:http://www.qianduanheidong.com/blog/article/248513/19b3ad803dae3402466f/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

15 0
收藏该文
已收藏

评论内容:(最多支持255个字符)