vue3中的computed、watchEffect、watch

一,computed

用法一:传入一个getter函数
setup() {
	const firstName = ref('李')
	const lastName = ref('华')
	// 传入一个getter函数
	const fullName = computed(() => firstName.vaule + lastName.value);
}
用法二:传入一个对象,对象包含getter/setter
setup() {
	const firstName = ref('李')
	const lastName = ref('华')
	
	const fullName = computed({
		get: () => firstName.value + lastName.value,
		set(newVaule) {
			// 这里可以写一些处理逻辑
		}
	})
}

二、watchEffect

当我们需要监听数据的变化时,可以使用watchEffect

  • watchEffect在代码第一次执行的时候会立即执行一次,并且会去收集依赖;
  • 只有收集的依赖发生变化时,watchEffect传入的函数才会再次执行;
1.使用方式
<script>
  import { ref, watchEffect } from 'vue';
  export default {
    setup() {
      const name = ref("zhangsan");
      const age = ref(20);

      const changeName = () => name.value = "lisi"
      const changeAge = () => age.value++
      // watchEffect: 自动收集响应式的依赖,watchEffect只收集到了name属性,所以当name的值发生变化时,会执行里面的函数
      // age变化不会执行watchEffect里面的函数
      watchEffect(() => {
        console.log("name:", name.value);
      });

      return {
        name,
        age,
        changeName,
        changeAge
      }
    }
  }
</script>
2.watchEffect停止侦听
<script>
  import { ref, watchEffect } from 'vue';

  export default {
    setup() {
      const name = ref("zhangsan");
      const age = ref(20);
	  // 用一个变量来接收watchEffect的返回值,返回值是一个函数
	  const stop = watchEffect(() => {
        console.log("name:", name.value, "age:", age.value);
      });

      const changeAge = () => {
        age.value++;
        if (age.value > 25) {
          // 执行watchEffect的返回值,就可以停止侦听
          stop();
        }
      }
    }
  }
</script>
3.flush参数:需要等DOM元素挂载完,再去获取DOM元素的内容
<template>
  <div>
    <h2 ref="title">888888</h2>
  </div>
</template>

<script>
  import { ref, watchEffect } from 'vue';

  export default {
    setup() {
      const title = ref(null);

      watchEffect(() => {
        console.log(title.value);
      }, {
        flush: "post"
      })

      return {
        title
      }
    }
  }
</script>

三、watch

  • watch需要指定侦听的数据源
  • 只有当侦听的数据发生变化时才会执行回调
<template>
  <div>
    <h2 ref="title">{{info.name}}</h2>
    <button @click="changeData">修改数据</button>
  </div>
</template>

<script>
  import { ref, reactive, watch } from 'vue';

  export default {
    setup() {
      const info = reactive({name: "why", age: 18});

      // 1.侦听watch时,传入一个getter函数
      watch(() => info.name, (newValue, oldValue) => {
        console.log("newValue:", newValue, "oldValue:", oldValue);
      })

      // 2.传入一个可响应式对象: reactive对象/ref对象
      // 情况一: reactive 对象获取到的newValue和oldValue本身都是reactive对象
      watch(info, (newValue, oldValue) => {
         console.log("newValue:", newValue, "oldValue:", oldValue);
      })
      // 情况二: ref对象获取newValue和oldValue是value值的本身
      const name = ref("why");
      watch(name, (newValue, oldValue) => {
        console.log("newValue:", newValue, "oldValue:", oldValue);
      })
      
      // 3.如果希望newValue和oldValue是一个普通的对象
      watch(() => {
        return {...info}
      }, (newValue, oldValue) => {
        console.log("newValue:", newValue, "oldValue:", oldValue);
      })

      const changeData = () => {
        info.name = "kobe";
      }

      return {
        changeData,
        info
      }
    }
  }
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 ,`watch` 和 `computed` 的用法和 Vue 2 略有不同。 ## watch ### 监听单个响应式数据 在 Vue 3 ,你可以使用 `watch` 函数来监听一个响应式数据的变化。例如: ```javascript import { watch } from 'vue'; // 在 setup 函数使用 watch setup() { const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`count 从 ${oldValue} 变为 ${newValue}`); }); return { count }; } ``` 在上面的例子,我们使用 `watch` 函数监听了 `count` 的变化,并在回调函数输出了新旧值。 ### 监听多个响应式数据 如果需要监听多个响应式数据的变化,你可以传入一个对象,对象的属性名是需要监听的数据,属性值是回调函数。例如: ```javascript import { watch, ref } from 'vue'; // 在 setup 函数使用 watch setup() { const count1 = ref(0); const count2 = ref(0); watch({ count1: (newValue, oldValue) => { console.log(`count1 从 ${oldValue} 变为 ${newValue}`); }, count2: (newValue, oldValue) => { console.log(`count2 从 ${oldValue} 变为 ${newValue}`); } }); return { count1, count2 }; } ``` ### 监听非响应式数据 如果需要监听非响应式数据的变化,你可以使用 `watchEffect` 函数。例如: ```javascript import { watchEffect } from 'vue'; // 在 setup 函数使用 watchEffect setup() { let count = 0; watchEffect(() => { console.log(`count 变为 ${count}`); }); return { count }; } ``` ## computedVue 3 ,你可以使用 `computed` 函数来创建计算属性。例如: ```javascript import { computed, ref } from 'vue'; // 在 setup 函数使用 computed setup() { const count = ref(0); const doubleCount = computed(() => { return count.value * 2; }); return { count, doubleCount }; } ``` 在上面的例子,我们创建了一个计算属性 `doubleCount`,它的值是 `count` 的两倍。当 `count` 改变时,`doubleCount` 也会自动更新。 需要注意的是,计算属性的返回值必须是一个响应式数据。如果返回的是普通数据,那么计算属性就没有意义了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值