美文网首页
watch和watchEffect的区别

watch和watchEffect的区别

作者: 夏日冰红茶 | 来源:发表于2024-08-09 17:07 被阅读0次

    watch和watchEffect都是vue中用来监测数据变化的函数。

    比如示例:
         <template>
           <div>
              <input v-model="inputValue" />
              <p>正序:{{inputValue}}</p>
              <p>倒序:{{reverseValue}}</p>
            </div>
        </template>
    
    用watch实现:
    <script setup>
    import { reactive, ref, watch, watchEffect}  from 'vue'
    const inputValue = ref("");
    const reverseValue = ref("");
    watch(inputValue,(newValue)=>{
      reverseValue.value = newValue.split("").reverse().join("");
    });
    </script>
    
    用watchEffect实现:
    import { reactive, ref, watch, watchEffect}  from 'vue'
    const inputValue = ref("");
    const reverseValue = ref("");
    watchEffect(()=>{
      reverseValue.value = inputValue.value.split("").reverse().join("");
    });
    
    两者之间的区别:

    1、watch是懒执行的,只有在数据变化时才会执行回调函数。
    watchEffect则是立即执行的,不管数据是否变化。

    2、watchEffect的函数会立即执行一次,并在依赖的数据变化时再次执行。
    watch的回调函数只有在监听数据源时变化时才会执行,不会立即执行。

    3、watch是监听单个数据源,可以设置immediate、deep、flush选项,可以获取新值和旧值;
    watchEffect则是监听一组数据源,不能设置immediate和deep选项, 不能获取新值和旧值。

    相关文章

      网友评论

          本文标题:watch和watchEffect的区别

          本文链接:https://www.haomeiwen.com/subject/qbhkkjtx.html