大家好,本篇文章我們繼續(xù)學(xué)習(xí)和 Vue 相關(guān)的內(nèi)容,今天我們歸納總結(jié)下如何使用 watch 監(jiān)聽組件中的數(shù)據(jù)變化,以及 computed 和 watch 的區(qū)別。
watch 是 Vue.js 中用于監(jiān)聽數(shù)據(jù)變化的一種機(jī)制。它允許我們在數(shù)據(jù)發(fā)生變化時(shí)執(zhí)行特定的操作。
在 Vue 中使用 watch 的方法如下:
在 Vue 組件中,定義一個(gè) watch 對象,其中包含要監(jiān)聽的數(shù)據(jù)屬性以及對應(yīng)的回調(diào)函數(shù)。
watch: { dataName: function(newValue, oldValue) { // code }}
其中,dataName 是要監(jiān)聽的數(shù)據(jù)名稱,newValue 是新的值,oldValue 是舊的值。
在 Vue 實(shí)例中,使用 $watch() 方法進(jìn)行監(jiān)聽
vm.$watch('someData', function(newVal, oldVal) { // do something with newVal});
注意:watch 回調(diào)函數(shù)會(huì)在偵聽的數(shù)據(jù)發(fā)生變化時(shí)立即執(zhí)行,而 computed 屬性只有在其依賴的數(shù)據(jù)發(fā)生變化時(shí)才會(huì)計(jì)算。
watch 通常用于監(jiān)聽一個(gè)數(shù)據(jù)的變化并執(zhí)行復(fù)雜的業(yè)務(wù)邏輯,例如在某個(gè)數(shù)據(jù)變化后需要進(jìn)行 HTTP 請求或者調(diào)用其他函數(shù)。
下面是一個(gè)簡單的 watch 的例子:
<template> <div> <input v-model="message" type="text" placeholder="請輸入內(nèi)容"> <p>{{ message }}</p> </div></template><script>export default { data() { return { message: '', } }, watch: { message: function (newVal, oldVal) { console.log('message changed from ' + oldVal + ' to ' + newVal) } },}</script>
在這個(gè)例子中,我們使用了 watch 來監(jiān)聽 message 的變化,并在數(shù)據(jù)變化時(shí)打印出更改前后的值。
當(dāng)然,watch 還可以接收一個(gè)對象,其中可以定義多個(gè)監(jiān)聽器。這里有一個(gè)例子,它監(jiān)聽了多個(gè)數(shù)據(jù):
watch: { firstName: function (newVal, oldVal) { console.log('firstName changed from ' + oldVal + ' to ' + newVal) }, lastName: function (newVal, oldVal) { console.log('lastName changed from ' + oldVal + ' to ' + newVal) }}
深度觀察 (deep: true):如果你希望對對象內(nèi)部屬性的變化進(jìn)行監(jiān)聽,可以使用 deep: true 選項(xiàng)。
data() { user: { name: 'John', age: 25 }},watch: { 'user.name': function (val) { console.log('user name changed:', val) }}
在這個(gè)例子中,我們監(jiān)聽了 user 對象中的 name 屬性,當(dāng)該屬性變化時(shí),會(huì)執(zhí)行回調(diào)函數(shù)。
設(shè)置初始值 (immediate: true):如果你希望 watch 在組件創(chuàng)建時(shí)立即執(zhí)行一次,可以使用 immediate: true 選項(xiàng)。
data() { count: 0},watch: { count: { handler: function (val, oldVal) { console.log('count changed'); }, immediate: true }}
異步處理 (handler):watch 的回調(diào)函數(shù)是異步執(zhí)行的,這意味著如果有多個(gè)值在短時(shí)間內(nèi)發(fā)生變化,回調(diào)函數(shù)只會(huì)在這些變化結(jié)束后執(zhí)行一次。
watch: { searchText: function (val) { this.searching = true setTimeout(() => { this.searchData(val) this.searching = false }, 500) }}
在這個(gè)例子中,我們監(jiān)聽了 searchText 屬性,并在數(shù)據(jù)變化后延遲 500 毫秒執(zhí)行搜索操作。
使用 watch 觀察器實(shí)現(xiàn)自動(dòng)保存。
data() { content: ''},watch: { content: function (val) { localStorage.setItem('content', val) }}
在這個(gè)例子中,我們監(jiān)聽了 content 屬性,并在數(shù)據(jù)變化時(shí)自動(dòng)保存到本地存儲(chǔ)中。
watch 監(jiān)聽器還有許多其他的應(yīng)用場景,例如:
<template> <form> <label> Email: <input v-model="email" @keyup="validateEmail"/> </label> <p v-if="error">{{ error }}</p> </form></template><script>export default { data() { return { email: '', error: '' } }, watch: { email: { immediate: true, handler(val) { if (!val.includes('@')) { this.error = 'Invalid email address' } else { this.error = '' } } } }}</script>
<template> <div> <div id="map"></div> </div></template><script>export default { data() { return { userLocation: { lat: 0, lng: 0 }, map: null } }, mounted() { this.map = new google.maps.Map(document.getElementById("map"), { center: { lat: 0, lng: 0 }, zoom: 8 }); navigator.geolocation.getCurrentPosition(position => { this.userLocation = { lat: position.coords.latitude, lng: position.coords.longitude } }); }, watch: { userLocation: { deep: true, handler(val) { this.map.setCenter(val); new google.maps.Marker({ position: val, map: this.map }); } } }}</script>
在這個(gè)示例中,我們使用了 watch 來監(jiān)聽 userLocation 的變化,在用戶位置發(fā)生變化時(shí),使用 setCenter 方法將地圖中心設(shè)置為用戶當(dāng)前位置,并使用 google maps API 在地圖上添加一個(gè)標(biāo)記,顯示用戶當(dāng)前位置。
注意:這個(gè)例子需要引入 google maps 的 js 文件。
<template> <!-- 省略 --></template><script>export default { watch: { $route(to, from) { // 根據(jù)路由變化執(zhí)行相應(yīng)操作 if (to.path === '/home') { this.getHomeData() } else if (to.path === '/about') { this.getAboutData() } } }, methods: { getHomeData() { // 獲取首頁數(shù)據(jù) }, getAboutData() { // 獲取關(guān)于頁數(shù)據(jù) } }}</script>
<template> <!-- 省略 --></template><script>export default { data() { return { windowWidth: 0 } }, created() { this.windowWidth = window.innerWidth }, watch: { windowWidth(newWidth, oldWidth) { // 監(jiān)聽窗口大小變化并調(diào)整布局 if (newWidth < 768) { // 小屏幕布局 } else { // 大屏幕布局 } } }, mounted() { window.addEventListener('resize', () => { this.windowWidth = window.innerWidth }) }}</script>
<template> <div class="container" ref="container" @scroll="handleScroll"> <img v-for="(item, index) in images" :key="index" :src="item.src" v-show="item.isLoaded" /> </div></template><script>export default { data() { return { images: [ { src: 'image1.jpg', isLoaded: false }, { src: 'image2.jpg', isLoaded: false }, { src: 'image3.jpg', isLoaded: false }, // ... ] } }, mounted() { // 初始化加載第一屏圖片 this.lazyLoad(); }, methods: { handleScroll() { this.lazyLoad(); }, lazyLoad() { const container = this.$refs.container; const imageList = Array.from(container.querySelectorAll('img')); // 遍歷圖片列表,如果圖片進(jìn)入了可視區(qū)域,就加載 imageList.forEach(img => { if (this.isInViewport(img)) { img.src = img.dataset.src; img.isLoaded = true; } }); }, isInViewport(img) { // 獲取圖片相對于視口的位置 const rect = img.getBoundingClientRect(); // 判斷圖片是否進(jìn)入了可視區(qū)域 return rect.top < window.innerHeight && rect.bottom > 0; } }, watch: { images: { handler: function(newVal, oldVal) { // 每當(dāng)圖片加載完成時(shí),就移除已加載圖片的 isLoaded 屬性 newVal.forEach((item, index) => { if (item.isLoaded) { this.$set(this.images[index], 'isLoaded', false); } }); }, deep: true } }}</script>
注意:需要注意的是,在這個(gè)案例中,因?yàn)閕mages數(shù)組中的對象被改變了,所以需要設(shè)置deep: true來監(jiān)聽對象
總之,watch 是一個(gè)非常強(qiáng)大和靈活的功能,它可以在數(shù)據(jù)變化時(shí)執(zhí)行任何操作,并且可以與 computed 計(jì)算屬性配合使用,來實(shí)現(xiàn)更復(fù)雜的邏輯。
watch和computed都可以監(jiān)聽Vue實(shí)例中的數(shù)據(jù)變化,但是它們有著明顯的不同。
watch | computed |
用于監(jiān)聽某個(gè)特定的數(shù)據(jù)變化。 | 用于計(jì)算屬性,可以計(jì)算出一個(gè)新的值。 |
每次數(shù)據(jù)變化都會(huì)觸發(fā)回調(diào)函數(shù)。 | 僅在相關(guān)依賴發(fā)生改變時(shí)才會(huì)觸發(fā)重新計(jì)算。 |
適用于異步操作或復(fù)雜邏輯。 | 適用于簡單計(jì)算。 |
不可以在HTML模板中使用 | 可以在HTML模板中使用 |
沒有返回值 | 有返回值/getter |
可以修改data中的數(shù)據(jù) | 也可以使用setters 修改 data 中的數(shù)據(jù) |
總之,如果你需要在數(shù)據(jù)變化時(shí)執(zhí)行異步操作或復(fù)雜邏輯,使用watch是更好的選擇;如果你需要在數(shù)據(jù)變化時(shí)計(jì)算出一個(gè)新值,使用computed是更好的選擇。
watch的性能取決于你的代碼實(shí)現(xiàn)方式和監(jiān)聽的數(shù)據(jù)量。
所以,在使用watch時(shí),應(yīng)該注意監(jiān)聽的數(shù)據(jù)量,并且在watch回調(diào)函數(shù)中盡量少執(zhí)行復(fù)雜的邏輯.總之,watch監(jiān)聽數(shù)據(jù)更新并執(zhí)行回調(diào)函數(shù),性能會(huì)受到監(jiān)聽數(shù)據(jù)量和回調(diào)函數(shù)實(shí)現(xiàn)方式的影響,如果有性能問題,應(yīng)該優(yōu)化監(jiān)聽的數(shù)據(jù)量和回調(diào)函數(shù)的實(shí)現(xiàn)方式.
今天的文章就介紹到這里,關(guān)于 watch 的用法你學(xué)會(huì)了,希望今天的文章能幫助到你,感謝你的閱讀。
本文鏈接:http://www.www897cc.com/showinfo-26-45498-0.htmlVue3 學(xué)習(xí)筆記,如何使用 Watch 監(jiān)聽數(shù)據(jù)變化
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: Node在項(xiàng)目中應(yīng)用案例之給幾百個(gè)下拉框統(tǒng)一加Filterable實(shí)現(xiàn)可搜索