Loading... <h1>Vue3 中的 watch 和 watchEffect 详解</h1> <p>在 vue 3 组件化开发中 中使用 watch , watchEffect 都需要import导入</p> <p><code> import { watch, watchEffect } from 'vue' </code></p> <h2>watch</h2> <h4>属性</h4> <ul> <li>watch 具备一定的惰性</li> <li>可以拿到原始值和当前值</li> <li>可以侦听多个数据的变换,用一个侦听器承载</li> </ul> <h4>传参</h4> <ul> <li>第一个参数,需要传递一个需要监听的 function 、ref 、reactive object</li> <li>第二个参数,用来接受数据原始值和当前值</li> <li>第三个参数,传递 watch 的高级配置项 例如 immediate: true</li> </ul> <p>一、监听基础类型</p> <pre><code class="language-vue">const count = ref(0) watch(count, (newValue, oldValue) => { console.log('watch' + newValue, oldValue) })</code></pre> <p>二、监听复杂类型</p> <p>在实际开发中,我们经常需要监听一个复杂的类型,具体写法如下</p> <pre><code class="language-vue">const boy = reactive({ name: '小小孩子们', blog: 'www.xxhzm.cn', friend: { friend1 : '小明', friend2 : '小红' } })</code></pre> <ol> <li> <p>监听整个对象</p> <pre><code class="language-vue">watch(boy, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue); console.log(newValue.friend); }) boy.name = 'Little children' boy.friend.friend3 = '小王'</code></pre> <p>第一个参数传入我们要监听的对象,当监听的对象里面的任意一个属性发生变化,watch 方法便会触发。</p> </li> <li> <p>监听对象中的某个属性</p> <pre><code class="language-vue">// 如果我们直接写 boy.name watch(boy.name, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue) }) // vue会提示我们,监听的对象需要是一个 function 或者 ref 或者是一个 reactive object // 正确的写法是: watch(() => boy.name, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue) }) boy.name = 'Little children'</code></pre> </li> <li> <p>监听对象的所有属性</p> <pre><code class="language-vue">watch(() => boy, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue) }, { immediate: true }) boy.name = 'Little children'</code></pre> </li> <li> <p>监听多个数据</p> <p>watch 里面可以接收一个数组</p> <p>无论数组里面的哪一个数据发生变化,都会执行侦听器</p> <pre><code class="language-vue">watch([()=> boy.name, count], ([newName, newCount], [oldName, oldCount]) => { console.log(newName + '---' + oldName) console.log(newCount + '---' + oldCount) }) boy.name = 'Little children'</code></pre> </li> </ol> <h2>watchEffect</h2> <h4>属性</h4> <ul> <li>立即执行的,没有惰性 </li> <li>不需要传递要侦听的内容,会自动感知代码依赖,不需要传递很多参数,只需要一个回调函数</li> <li>不能获取之前数据的值</li> </ul> <p>一、监听基础类型</p> <pre><code class="language-vue">const count = ref(0) watchEffect(() => { console.log(count.value) }) count.value ++</code></pre> 猜你想看 使用nginx反代jsdelivr 使用shell脚本实现服务器CPU负载过高自动推送 vue3中vuex对比pinia tcping不是windows默认命令, tcping怎么安装? JS图片轮播 每日一学:PHP 中的array_udiff_assoc函数详解 nuxt3状态管理 每日一学:PHP 中的array_slice函数详解 Vue+axios判断用户名是否被占用 vue2使用ajax发送网络请求 最后修改:2022 年 06 月 05 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏
1 条评论
博主真是太厉害了!!!